views:

105

answers:

1

Possible Duplicates:
Using do block vs brackets {}
What is the difference or value of these block coding styles in Ruby?

Why does:

test = [1, 1, 1].collect do |te|
    te + 10
end
puts test

Works, but not:

puts test = [1, 1, 1].collect do |te|
    te + 10
end

And yet this works:

puts test = [1, 1, 1].collect { |te|
    te + 10
}

Is there a difference between the do/end construct and the { } construct for blocks I am not aware of?

+10  A: 

In the "not working" case, the block is actually attached to the puts call, not to the collect call. {} binds more tightly than do.

The explicit brackets below demonstrate the difference in the way Ruby interprets the above statements:

puts(test = [1, 1, 1].collect) do |te|
    te + 10
end

puts test = ([1, 1, 1].collect {|te|
    te + 10
})
Chris Jester-Young
Is there a general rule you can follow to predict this kind of behavior?
didibus
Well, to be sure, check the precedence rules (http://www.ruby-doc.org/docs/ProgrammingRuby/language.html#table_18.4). But as a rule of thumb, I always treat do...end as a code block, and {} as a function; also, never put a do...end inside a {}.
Shadowfirebird