A question from Ruby-Forum:
http://www.ruby-forum.org/bb/viewtopic.php?t=13
If I do this:
Code:
a = [1, 2, 3]
a.each do |x|
puts x
if x == 2 then break; end
endIt works (prints 1, 2 then stops), but returns nil. Normally a.each
should return a.I need an iterator that will return all elements processed until the
break. E.g.Code:
class Array
def each_with_a_twist
self.each_with_index do
>element, index|
yield element
>>> INTERCEPT THE BREAK <<<
break self[0, index]
end
end
endIs it possible?
I've come up with the following suggestion:
class A
def a
yield
ensure puts "after block"; return 1
end
end
I can see that this code is not good enough, because it doesn't
differentiate between the block terminated by break and the block
terminated by an error. What would be the Ruby Way here?
Alex