Skip to content

Instantly share code, notes, and snippets.

@caius
Created February 10, 2011 22:29
Show Gist options
  • Select an option

  • Save caius/821496 to your computer and use it in GitHub Desktop.

Select an option

Save caius/821496 to your computer and use it in GitHub Desktop.
#kch: Do we really not have a helper method for array.inject({}){|h,(k,v)|h[k]=v;h}? Not a day goes by that I don't type this.
array = [[1, 2], [3, 4]]
array.inject({}) {|h,(k,v)| h[k]=v; h } # => {1=>2, 3=>4}
Hash[*array.flatten] # => {1=>2, 3=>4}
@kch
Copy link

kch commented Feb 10, 2011

Safer general solution:

a = [:a,[1,2]], [:b,[3,4]]
p a.inject({}){|h,(k,v)|h[k]=v;h}  # => {:a=>[1, 2], :b=>[3, 4]}  <--- reference
p Hash[*a.flatten]                 # => {:a=>1, 2=>:b, 3=>4}      <--- WRONG
p Hash[*a.flatten(1)]              # => {:a=>[1, 2], :b=>[3, 4]}  <--- Safe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment