John Burley John Burley - 3 months ago 12
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|
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}"
}

Answer

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.