From: "dsisnero (Dominic Sisneros)" Date: 2012-08-22T04:42:05+09:00 Subject: [ruby-core:47265] [ruby-trunk - Feature #6824] StopIteration gets a source method Issue #6824 has been updated by dsisnero (Dominic Sisneros). I use the following method to weave enumerators together #Intersperse several iterables, until all are exhausted def weave(*enumerators) enums = enumerators.map{|e| e.to_enum} result = Enumerator.new do |y| while !enums.empty? loop_enum = enums.dup loop_enum.each_with_index do |enum,i| begin y << enum.next rescue StopIteration #raise StopIteration if enums.empty? enums.delete_at(i) end end end #raise StopIteration end end ---------------------------------------- Feature #6824: StopIteration gets a source method https://bugs.ruby-lang.org/issues/6824#change-28961 Author: jasiek (Jan Szumiec) Status: Open Priority: Normal Assignee: Category: core Target version: 2.0.0 =begin I'd like to add a method to StopIteration that returns an instance of the enumerator which triggered this exception. Eg: enum = [].each begin enum.next rescue StopIteration => ex puts "same" if ex.source == enum end This is useful when you're merging multiple collections using min/max - when one of the collections is exhausted it can be easily ignored. enumerators = 100.times.map do rand(100).times.map do rand end.sort.each end merged = [] while !enumerators.empty? begin enumerators.map(&:peek) values = enumerators.map(&:next) merged += values.sort rescue StopIteration => e enumerators.delete(e.source) retry end end fail unless merged != merged.sort Attached is a patch against trunk. =end -- http://bugs.ruby-lang.org/