Module: Enumerable
- Defined in:
- lib/casual_support/enumerable/index_to.rb,
lib/casual_support/enumerable/duplicates.rb
Instance Method Summary collapse
-
#duplicates {|elem| ... } ⇒ Enumerable
Returns the first duplicate of each element, preserving order of appearance.
-
#index_to {|elem| ... } ⇒ Hash
Converts an
Enumerableinto aHashby using its elements as keys and extracting values from each.
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]
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.
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 |