Grandpa Grandpa - 1 year ago 108
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 {.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download