module Enumerable

Public Instance Methods

each_uniq { |obj| ... } click to toggle source

Yields all unique values found in enum

# 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_element() click to toggle source

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

# 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