Module: Enumerable

Included in:
NullEnumerator, SequenceEnumerator
Defined in:
lib/utilrb/enumerable/uniq.rb,
lib/utilrb/enumerable/random_element.rb

Instance Method Summary collapse

Instance Method Details

#each_uniqObject

call-seq:

each_uniq { |obj| ... }

Yields all unique values found in enum


56
57
58
59
60
61
62
63
64
# File 'lib/utilrb/enumerable/uniq.rb', line 56

def each_uniq
    seen = Set.new
    each do |obj|
        if !seen.include?(obj)
            seen << obj
            yield(obj)
        end
    end
end

#random_elementObject

Returns a random element in the enumerable. In the worst case scenario, it converts the enumerable into an array


9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/utilrb/enumerable/random_element.rb', line 9

def random_element
	if respond_to?(:to_ary)
 to_ary.random_element
	elsif respond_to?(:size)
 return if size == 0
 element = rand(size)
 each_with_index { |e, i| return e if i == element }
 raise "something wrong here ..."
	elsif respond_to?(:to_a)
 to_a.random_element
	else
 raise ArgumentError, "cannot ue #random_element on this enumerable"
	end
end