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

Convert to result array of Hash.to_a or Hash.sort back to a hash (See related posts)

hash_var = array_var..inject({}) {|h, elem| h[elem[0]]=elem[1]; h}

Comments on this post

brotherlarry posts on Jun 09, 2006 at 20:21
This does the same thing:

Hash[*array_var.flatten]
NickHowell posts on Apr 25, 2007 at 18:48
Actually, that'll break if your Hash contains array values:

Hash[ *{ :x => 1, :y => 2, :z => [3,4] }.to_a.flatten ]
ArgumentError: odd number of arguments for Hash
        from (irb):1:in `[]'
        from (irb):1

{ :x => 1, :y => 2, :z => [3,4] }.to_a.inject({}) { |m, e| m[e[0]] = e[1]; m }
=> {:y=>2, :x=>1, :z=>[3, 4]}


The discrepancy is because flatten recurses.

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts