3
puts [1,2,3].map do |x| 
  x + 1 
end.inspect

With ruby 1.9.2 this returns

<Enumerator:0x0000010086be50>

ruby 1.8.7:

# 1
# 2
# 3

assigning a variable...

x = [1,2,3].map do |x| 
  x + 1 
end.inspect

puts x

[2, 3, 4]

Moustache blocks work as expected:

puts [1,2,3].map { |x| x + 1 }.inspect

[2, 3, 4]

sunkencity
  • 3,482
  • 1
  • 22
  • 19
  • See also [Ruby Block Syntax Error](http://StackOverflow.Com/q/6854283/), [Code block passed to `each` works with brackets but not with `do`-`end` (ruby)](http://StackOverflow.Com/q/6718340/), [Block definition - difference between braces and `do`-`end` ?](http://StackOverflow.Com/q/6179442/), [Ruby multiline block without `do` `end`](http://StackOverflow.Com/q/3680097/), [Using `do` block vs brackets `{}`](http://StackOverflow.Com/q/2122380/), [What is the difference or value of these block coding styles in Ruby?](http://StackOverflow.Com/q/533008/), … – Jörg W Mittag Sep 05 '11 at 14:34
  • … [Ruby block and unparenthesized arguments](http://StackOverflow.Com/q/420147/), [One-liner shoulda syntax using braces](http://StackOverflow.Com/q/4534436/#4534730) and [`do`..`end` vs curly braces for blocks in Ruby](http://StackOverflow.Com/q/5587264/). – Jörg W Mittag Sep 05 '11 at 14:36
  • @Jorg: Are you trying to imply that this may be a duplicate question? – Andrew Grimm Sep 07 '11 at 23:30

1 Answers1

9
puts [1,2,3].map do |x| 
  x + 1 
end.inspect

Is parsed as:

puts([1,2,3].map) do |x| 
  x + 1 
end.inspect

I.e. map is called without a block (which will make it return the unchanged array in 1.8 and an enumerator in 1.9) and the block is passed to puts (which will just ignore it).

The reason that it works with {} instead of do end is that {} has different precedence so it's parsed as:

puts([1,2,3].map { |x| x + 1 }.inspect)

Similarly the version using a variable works because in that case there is simply no ambiguity.

sepp2k
  • 363,768
  • 54
  • 674
  • 675