From: Alexey Verkhovsky Date: 2004-09-16T03:50:06+09:00 Subject: 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 > end > > It 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 > end > > Is 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