Using do block vs braces {}

Alan Storm picture Alan Storm · Jan 23, 2010 · Viewed 58.8k times · Source

New to ruby, put on your newbie gloves.

Is there any difference (obscure or practical) between the following two snippets?

my_array = [:uno, :dos, :tres]
my_array.each { |item| 
    puts item
}

my_array = [:uno, :dos, :tres]
my_array.each do |item| 
    puts item
end

I realize the brace syntax would allow you to place the block on one line

my_array.each { |item| puts item }

but outside of that are there any compelling reasons to use one syntax over the other?

Answer

YOU picture YOU · Jan 23, 2010

Ruby cookbook says bracket syntax has higher precedence order than do..end

Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:

1.upto 3 do |x|
  puts x
end

1.upto 3 { |x| puts x }
# SyntaxError: compile error

Second example only works when parentheses is used, 1.upto(3) { |x| puts x }