top | item 44057472

(no title)

pmahoney | 9 months ago

Can you explain further? I'm not sure I follow.

> How do you as a method author opt in to distinguishing between [break and next] after yielding to a block?

I don't use Ruby much lately, but if I yield to a block which calls break, control will pass to the code following the block (and not back to my method). If the block calls next or simply finishes, control passes back to me though I cannot know if next was called or not (but do I care? I can go ahead and yield the next element of a collection either way)

discuss

order

chowells|9 months ago

Ah, you're right. They do have observably different behavior. But I can't even close an open file handle after a break. That's still pretty miserable.

dragonwriter|9 months ago

> But I can't even close an open file handle after a break.

Yes, you can. That's what ensure (the Ruby equivalent of "finally") is for. Or, better using File.open with a block where you do the work, which uses ensure under the hood.

HellzStormer|9 months ago

Yes you can, you use a finally clause around your call to yield, as you would already do to handle possible exceptions happening in the block. So no extra consideration is needed.