Skip to content

Instantly share code, notes, and snippets.

@lemanchester
Created October 15, 2015 20:21
Show Gist options
  • Save lemanchester/d9dc4c0a186a8253438e to your computer and use it in GitHub Desktop.
Save lemanchester/d9dc4c0a186a8253438e to your computer and use it in GitHub Desktop.
Convert Ruby Array to Hash

Convert Array to Hash

fruits = [[6, "apple"], [7, "orange"], [8, "grape"], [24, "banana"], [30, "strawberry"], [66, "lemon"]]
Hash[*fruits.flatten(1)] # => {6=>"apple", 7=>"orange", 8=>"grape", 24=>"banana", 30=>"strawberry", 66=>"lemon"}
Hash[fruits.map {|key, value| [key, value]}] # => {6=>"apple", 7=>"orange", 8=>"grape", 24=>"banana", 30=>"strawberry", 66=>"lemon"}
Hash[fruits] # => {6=>"apple", 7=>"orange", 8=>"grape", 24=>"banana", 30=>"strawberry", 66=>"lemon"}

Ruby > 2.1.0

fruits.to_h # => {6=>"apple", 7=>"orange", 8=>"grape", 24=>"banana", 30=>"strawberry", 66=>"lemon"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment