Grandpa Grandpa - 1 year ago 88
Ruby Question

Ruby do/end vs braces

Why does this map expression produce different results depending on whether I use braces or do/end?

a = [1,2,3,4,5]

p { |n|
#=> [2,4,6,8,10]

p do |n|
#=> [1,2,3,4,5]

Answer Source

That's because the second line is interpreted as:

p( do ... end

instead of:

p( do ... end)

The grammar is ambiguous in this case and do doesn't seem to bind as strongly as {.