2

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?

Community
  • 1
  • 1
Didier A.
  • 4,609
  • 2
  • 43
  • 45
  • This question is an exact duplicate of http://StackOverflow.Com/questions/533008/ and http://StackOverflow.Com/questions/2122380/ and probably a dozen others. – Jörg W Mittag Feb 12 '10 at 10:24
  • Most upvoted duplicate I saw : https://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby/5587403 – ymoreau Aug 16 '18 at 10:40

1 Answers1

10

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
})
EmFi
  • 23,435
  • 3
  • 57
  • 68
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Is there a general rule you can follow to predict this kind of behavior? – Didier A. Feb 12 '10 at 08:14
  • 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 Feb 12 '10 at 10:13