lib/core/facets/enumerable/collate.rb in facets-2.1.2 vs lib/core/facets/enumerable/collate.rb in facets-2.1.3

- old
+ new

@@ -1,46 +1,32 @@ -# TITLE: -# -# Enumerable Collate -# -# DESCRIPTION: -# -# Collate is a Hash collection method. -# -# AUTHORS: -# -# CREDIT 7ransVent -# -# NOTES: -# -# NOTE Hash#collate! is only useful for Hash. It is not generally -# applicable to Enumerable. -#++ +require 'enumerator' module Enumerable # Like <tt>#map</tt>/<tt>#collect</tt>, but generates a Hash. The block # is expected to return two values: the key and the value for the new hash. # # numbers = (1..3) - # squares = numbers.graph { |n| [n, n*n] } # { 1=>1, 2=>4, 3=>9 } - # sq_roots = numbers.graph { |n| [n*n, n] } # { 1=>1, 4=>2, 9=>3 } + # squares = numbers.collate { |n| [n, n*n] } # { 1=>1, 2=>4, 3=>9 } + # sq_roots = numbers.collate { |n| [n*n, n] } # { 1=>1, 4=>2, 9=>3 } + # + # CREDIT: Trans + # CREDIT: Andrew Dudzik (adudzik) def collate(&yld) if yld - inject({}) do |h,kv| - nk, nv = *yld[*kv].to_a.flatten + inject({}) do |h, *kv| # Used to be inject({}) do |h,kv| + r = *yld[*kv] # The *-op works differnt from to_a on single element hash!!! + nk, nv = *r # Used to be nk, nv = *yld[*kv].to_a.flatten h[nk] = nv h end else - Hash[*self.to_a.flatten] + Enumerator.new(self,:collate) # Used to be Hash[*self.to_a] or Hash[*self.to_a.flatten] end end - # Alias for #collate (THIS WILL BE DEPRECATED) - alias :graph :collate # Returns a new hash built by iterating through each key,value # pair and updating the new hash. #def collate #:yield: @@ -53,9 +39,12 @@ class Hash # In place version of #collate. + # + # NOTE Hash#collate! is only useful for Hash. It is not generally + # applicable to Enumerable. def collate!(&yld) replace(collate(&yld)) end