John Burley John Burley - 11 months ago 49
Ruby Question

What is the difference or value of these block coding styles in Ruby?

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

Thanks in advance!

1) cmds.each do |cmd|

2) cmds.each { |cmd|

Example code:

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

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

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

Answer Source

The rails team and many other rubyists prefer to use curly braces for one line blocks and do...end for multi-line ones.

The only functional difference between the two is that the precedence of a do...end block is lower than that of a {...} block.