4 ms·
You shouldn't have much difficulty, Ruby converts blocks to Procs whenever it needs an actual object. Their semantics are intentionally kept the same. This is u
by vinceguidry 1y ago
You shouldn't have much difficulty, Ruby converts blocks to Procs whenever it needs an actual object. Their semantics are intentionally kept the same. This is unlike lambdas, whose semantics are closer to methods.
Pass the wrong number of of arguments to a Proc or block, it will pass nil for missing args and omit extras. Pass the wrong number of arguments for a method or lambda and you get an ArgumentError. Use the return keyword in a lambda, it returns from the lambda, just like if you call return in a method. In a block or Proc, it returns from the calling method.
So I would feel comfortable leaning on them for refactoring as it's as Ruby intended. Just use lambdas when you want to turn methods into objects and Procs when you want to objectify blocks.
You should get ahold of a copy of Metaprogramming Ruby 2 if you find yourself refactoring a lot of Ruby. It's out of print, but ebooks are available.
- vidarh 1y agoJust to clarify here: Both lambdas and procs are Proc objects. Blocks gets turned into Proc objects when you take their value. So just be clear about whether you're talking about a proc or a Proc... > In a block or Proc, it returns from the calling method No, in block or a Proc it returns from the scope where it was defined. Usually this is the same, and so it doesn't usually matter much, but if you pass a proc or a block down to another method, then a return within the block will still return from the method where it was defined. This can occasionally be useful, as you can use it to pass in a predicate to a method that can control if/when you want to return, irrespective of how deeply nested.
- vidarh 1y agoToo late to edit now, and this is what I get for quibbling about casing: > No, in block or a Proc it returns from the scope where it was defined. Should of course read: > No, in a block or a proc it returns from the scope where it was defined.
- dragonwriter 1y ago> Use the return keyword in a lambda, it returns from the lambda, just like if you call return in a method. In a block or Proc, it returns from the calling method. In a block or proc, it returns from the method in which the block/proc was defined, not the calling method. These may or may not be the same; the proc may be called deeper in the call chain, or it might (erroneously) be called after the defining method had exited, producing a LocalJumpError. This also means that implicit returns from a block/proc have different semantics than explicit returns, unlike lambdas/methods where implicit returns have the same semantics as explicit returns. (From a block/proc, the last evaluated expressions behaves as if it were passed to "next" rather than "return", resulting in a local return to the calling method rather than a return from the defining method.)