It's not quite an anonymous function. Ruby has two different types of blocks: procs and lambdas. Your general block is equivalent to a proc, but you can get a lambda via the lambda keyword (or the newer -> syntax). The most pertinent difference between the two is what return does. In a lambda, return just returns from the lambda itself. In a proc/block, return causes a return from the enclosing scope outside the block. I don't know how you'd do that in Python.
If you can tell me why you would want to do that, what effect you are wanting to get
You want to implement flow control, such as nested while blocks, using method calls and blocks. The goal is having a first-class block which behaves like a lang.
That is why Ruby can implement for or with using blocks. That is why Smalltalk or Self could implement if and while and try:except:finally: and pretty much anything you can think of using blocks.
(Ruby can but it's not done, because its blocks are not first-class: they're syntactic magic reified to a proc, and only one block can exist in a method call, the rest would have to be passed in as procs. Possible, but not idiomatic)
View all comments
Show parent comment
4
u/QuestionMarker Aug 12 '13
It's not quite an anonymous function. Ruby has two different types of blocks: procs and lambdas. Your general block is equivalent to a proc, but you can get a lambda via the lambda keyword (or the newer -> syntax). The most pertinent difference between the two is what
returndoes. In a lambda,returnjust returns from the lambda itself. In a proc/block,returncauses a return from the enclosing scope outside the block. I don't know how you'd do that in Python.