Module: Enumerable

Defined in:
lib/casual_support/enumerable/index_to.rb,
lib/casual_support/enumerable/duplicates.rb

Instance Method Summary collapse

Instance Method Details

#duplicates {|elem| ... } ⇒ Enumerable

Returns the first duplicate of each element, preserving order of appearance. If a block is given, it will use the return value of the block for element comparison.

Examples:

%w[a a b c d c b a].duplicates == %w[a c b]
%w[A a B b].duplicates(&:upcase) == %w[a b]

Yields:

  • (elem)

    computes an indentifying value

Yield Parameters:

  • elem

    element from the Enumerable

Yield Returns:

  • value used for duplicate comparison

Returns:

  • (Enumerable)

    duplicate elements of the Enumerable



15
16
17
18
19
20
21
22
# File 'lib/casual_support/enumerable/duplicates.rb', line 15

def duplicates
  seen = Hash.new(0)
  if block_given?
    self.select{|elem| (seen[yield(elem)] += 1) == 2 }
  else
    self.select{|elem| (seen[elem] += 1) == 2 }
  end
end

#index_to {|elem| ... } ⇒ Hash

Converts an Enumerable into a Hash by using its elements as keys and extracting values from each.

Yields:

  • (elem)

    extracts a value

Yield Parameters:

  • elem

    element from the Enumerable

Yield Returns:

  • value to associate with the elem key

Returns:

  • (Hash)

    hash with the Enumerable‘s elements as keys



12
13
14
# File 'lib/casual_support/enumerable/index_to.rb', line 12

def index_to()
  self.reduce({}){|h, k| h.set!(k, (yield k)) }
end