3 ms·
> In your experience, is it ok to use Procs for example for extraction of block methods for cleanliness in refactors? In addition to the efficiency issues of u
by dragonwriter 1y ago
> In your experience, is it ok to use Procs for example for extraction of block methods for cleanliness in refactors?
In addition to the efficiency issues of unnecessarily reifying blocks into Proc objects, there are some sharp edges that can cut you doing this. For instance, Ruby blocks and procs [0] have return semantics based on where they are defined (specifically, "return" in a block or proc returns from the method in which the block/proc is defined.) So if you have two identical blocks used in two different methods, and those blocks have return calls, and you refactor them to shared Proc defined somewhere else that is used in each method, you will find that the behavior is broken, and when it returns it will either return from the wrong method or produce a LocalJumpError, depending on the exact structure of the program.
Local return from a block/proc is done with "next" instead of "return" (and if neither a next or return is hit, the last expression evaluated will be treated as an implicit "next"), so a block without an explicit return can be converted to a proc and reused in different places more safely.
[0] using the convention of lowercase "proc" to refer to a Proc object that does not have lambda semantics, whereas those created with Kernel#lambdda or the stabby-lambda syntax are "lambdas".