3 ms·
You can convert between blocks and Procs very easily. Ruby has several methods to let you do that, both as syntax and as methods. They are really two sides of t
by zoky 3y ago
You can convert between blocks and Procs very easily. Ruby has several methods to let you do that, both as syntax and as methods. They are really two sides of the same coin; a block can be thought of as a Proc that is intended for immediate usage (though this is convention, and of course nothing prevents you from converting a block into a Proc and stashing it away for later).
As for functions, Ruby doesn’t really have them—or, rather, blocks and Procs really are the closest you get to a function. Instead, since everything is an object, Ruby has methods instead of functions. Critically, because methods are defined on objects they have inherent object context, which is why you can’t treat a defined method as an anonymous function. Of course, there are ways to extract the method as a Proc and pass it to another object (with or without its object context). But having methods be objects the way they are in, for example, JavaScript would require extra magic under the hood, and lead to all sorts of context gotchas, which is probably why it doesn’t work that way.
- djur 3y agoIn 15+ years of writing Ruby for production I can't think of a single time where the distinction between blocks and procs caused a problem. Blocks are a syntactic element, procs are a data type (that you can construct with a block). I honestly don't even know where the problem is supposed to come from.
- amomchilov 3y agoIt comes up when you get in “ok this block is great, but now I want two of them”. Only one can be a block, the other needs to be a Proc, and now there’s this odd syntactic distinction