Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

to_hoa

   1  
   2  class Array
   3    
   4    # Make a hash of arrays out of an array
   5    # of somethings by involving each element.
   6    #
   7    # Pass a block returning each keys' name.
   8    #
   9    # Example usage:
  10    #
  11    # >> [1, 2, 3].to_hoa { |n| (n+96).chr }
  12    # => {"a"=>[1], "b"=>[2], "c"=>[3]}
  13    #
  14    # >> ['a', 'a', 'a', 'b', 'b', 'c'].to_hoa {|x|x}
  15    # => {"a"=>["a", "a", "a"], "b"=>["b", "b"], "c"=>["c"]}
  16      
  17    def to_hoa
  18      inject({}) { |h,v| (h[yield(v)] ||= []).push v; h }
  19    end
  20  
  21  end


update: RoR provides group_by, which does exactly the same using Enumerable (thanks Matt for pointing this out).
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS