Block definition – difference between braces and do-end?

The difference is precedence:

# Equivalent to puts( (1..10).map { |i| i*2 } )
> puts (1..10).map { |i| i*2 }
2
4
6
8
10
12
14
16
18
20
 => nil 

# Equivalent to puts( (1..10).map ) { |i| i*2 }
> puts (1..10).map do |i| i*2 end
#<Enumerator:0x928f24>
 => nil 

In the first case, the block is passed to map, and everything works properly.
In the second case, the block is passed to puts, which doesn’t do anything with it. map doesn’t receive a block and just returns an enumerator.

As for the syntax error, if you remove the space between print and ( everything works 😉

The difference is whether ruby is treating your parentheses as method argument delimiters, or whether it’s a generic statement grouping. I’m not sure of the exact difference there but it’s subtle and annoying

Leave a Comment