Project

General

Profile

Actions

Feature #6824

closed

StopIteration gets a source method

Added by jasiek (Jan Szumiec) over 11 years ago. Updated over 11 years ago.

Status:
Rejected
Target version:
[ruby-core:46929]

Description

=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


Files

stop.patch (2.32 KB) stop.patch jasiek (Jan Szumiec), 08/02/2012 06:45 PM

Updated by nobu (Nobuyoshi Nakada) over 11 years ago

  • Description updated (diff)

=begin
You should use (({assert_same})) instead of (({assert_equal})), I think.
=end

Updated by dsisnero (Dominic Sisneros) over 11 years ago

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

Updated by ko1 (Koichi Sasada) over 11 years ago

  • Assignee set to mame (Yusuke Endoh)

mame-san, could you judge this ticket?

Updated by mame (Yusuke Endoh) over 11 years ago

  • Status changed from Open to Rejected
  • Assignee changed from mame (Yusuke Endoh) to matz (Yukihiro Matsumoto)
  • Target version changed from 2.0.0 to 2.6

Hello,

jasiek (Jan Szumiec) wrote:

This is useful when you're merging multiple collections using min/max - when one of the collections is exhausted it can be easily ignored.

You are misunderstanding merge sort.
Your example does never work as intended.

fail unless merged != merged.sort

I bet this condition is inverted.

The proposal itself might be useful, but this ticket is based on misconception.
So I'm closing it. Please open another one if you wish.

--
Yusuke Endoh

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0