Class: UniqEnumerator

Inherits:
Enumerator
  • Object
show all
Defined in:
lib/utilrb/enumerable/uniq.rb

Overview

Enumerator object which removes duplicate entries. See also Object#enum_uniq and Enumerable#each_uniq

Instance Method Summary collapse

Constructor Details

#initialize(obj, enum_with, args, key = nil) ⇒ UniqEnumerator

Creates the enumerator on obj using the method enum_with to enumerate. The method will be called with the arguments in args.

If key is given, it is a proc object which should return the key on which we base ourselves to compare two objects. If it is not given, UniqEnumerator uses the object itself

See also Object#enum_uniq and Enumerable#each_uniq



16
17
18
19
20
# File 'lib/utilrb/enumerable/uniq.rb', line 16

def initialize(obj, enum_with, args, key = nil)
	super(obj, enum_with, *args)
	@key = key
	@result = Hash.new
end

Instance Method Details

#eachObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/utilrb/enumerable/uniq.rb', line 22

def each
	if block_given?
 @result.clear
 result = @result
 super() do |v|
		k = @key ? @key.call(v) : v

		if !result.has_key?(k)
  result[k] = v
  yield(v)
		end
 end

 result.values
	else
 self
	end
end