Grandpa Grandpa - 5 months ago 28
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 a.map { |n|
n*2
}
#=> [2,4,6,8,10]


p a.map do |n|
n*2
end
#=> [1,2,3,4,5]

Answer

That's because the second line is interpreted as:

p(a.map) do ... end

instead of:

p(a.map do ... end)

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