|
|
|
|
|
by vidarh
393 days ago
|
|
Your sentence structure did not at all make it clear that "the two" referred to next and break rather than proc and lambda. Assuming you don't care whether a "next" was actually called, but only whether you've exited the block and whether or not you exited it via a break, you can do this check in a number of ways, but it I will agree it's a bit dirty that sometimes you do need to rely on standard library functionality rather than language constructs if you want to do these things. Here's one way of doing it, since "break" within a Fiber triggers a LocalJumpError: def next_or_break(&block)
Fiber.new(&block).resume
:next_or_end_of_block_reached
rescue LocalJumpError
:break
end
p(next_or_break do next end)
p(next_or_break do break end)
|
|
You don't need to introduce a Fiber or rely on the standard library, you can just use the core language, leveraging the fact that code in ensure sections gets called even when you are returning "past" the calling method.
(You may need a dirty catch-all rescue so you can set a flag before reraising that lets you distinguish "bypassing direct return by exception" from "bypassing direct return by break or proc-semantics return", but that's still the core language, not standard library.)
I put example code in another comment: https://news.ycombinator.com/item?id=44065226