What is the difference or value of these block cod

2019-01-01 13:34发布

Which style is preferred? Is there a good reason for one vs. the other?

Thanks in advance!

1) cmds.each do |cmd|
   end

2) cmds.each { |cmd|
   }

Example code:

cmds = [ "create", "update", "list", "help" ]

# Block style one
#
cmds.each do |cmd|
  puts "loop1, cmd: #{cmd}"
end

# Block style two
#
cmds.each { |cmd|
  puts "loop2, cmd: #{cmd}"
}

7条回答
泪湿衣
2楼-- · 2019-01-01 14:26

Conventionally, using {} is reserved for single-line blocks, while do...end is for multi-line blocks.

Because of how {} are not used in Ruby as often as in other languages like C++ or Javascript, using do...end when given the chance instead of {} can help make your code more readable for other Rubyists.

Note that {} has precedence over do...end.

查看更多
登录 后发表回答