Re:Understanding Ruby Blocks, Procs and Lambdas
by aaronblohowiak on Tuesday December 23, 2008 @12:47AM
(#407318)
I respectfully disagree that the return keyword is more trouble than it is worth.
"return false if simple_question?" ... rest of the body
is a very useful thing to do. granted, you might say it is "programming by GOTO", but it lowers the indentation level, and so keeps me happy.
To the GP: we can also .to_proc on blocks.
Re:Understanding Ruby Blocks, Procs and Lambdas
by raganwald on Wednesday December 31, 2008 @04:25PM
(#415906)
Sorry I didn't see this when you posted it. The problem is not `return :foo if bar()`, it's something like `pizzles.each { |p| return :foo if p.bar() }`. In Ruby, that returns from the surrounding method, not from the block where it's defined.
You can decide for yourself if this behaviour of return more trouble than it's worth. I didn't say it was, I said that this definition is what forces a block to be something different from a proc, which makes the language more complicated.
If you had a block that was an actual object, it could outlive its enclosing environment. Calling return within it would reincarnate its enclosing environment. Calling return twice would fork time.
In other words, if a block was an object, the return keyword would create a continuation. This is a very expensive, very heavyweight feature in Ruby, and the whole point of blocks is to provide something cheap and lightweight.
Note that a proc or lambda has no such problem, since a return within it returns to whatever invokes the #call method of the proc or lambda.
Imagine how much simpler things would be if Matz had worked this all out and decided that the return keyword was more trouble than it was worth?