Why does a do/end block behave/return differently when a variable is assigned?
puts [1,2,3].map do |x|
x + 1
end.inspect
With ruby 1.9.2 this returns
&l开发者_如何学JAVAt;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]
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.
精彩评论