Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby convert an Array to Hash values with specific keys

Is there a way to pull the values from an array and assign them each a unique key in Ruby?

I want to be able to turn this array:

["12", "21", "1985"]

Into this hash:

{:month => "12", :day => "21", :year => "1985"}

I would rather not assign each value individually, like this:

arr = ["12", "21", "1985"]
bday_hash = {:month => arr[0], :day => arr[1], :year => arr[2]}
like image 995
djs Avatar asked May 26 '17 15:05

djs


3 Answers

You can use #zip

your_array = ["12", "21", "1985"]
keys = ['month', 'day', 'year']
keys.zip(your_array).to_h
like image 94
Md. Farhan Memon Avatar answered Nov 20 '22 09:11

Md. Farhan Memon


You can take array of keys, zip it with values and then convert to hash

keys = [:month, :day, :year]
values = ["12", "21", "1985"]
Hash[keys.zip(values)]
# => {:month=>"12", :day=>"21", :year=>"1985"} 
like image 8
mikdiet Avatar answered Nov 20 '22 07:11

mikdiet


Here are two other ways to obtain the desired hash.

arr_values = ["12", "21", "1985"]
arr_keys   = [:month, :day, :year]

[arr_keys, arr_values].transpose.to_h
  #=> {:month=>"12", :day=>"21", :year=>"1985"}

arr_keys.each_index.with_object({}) { |i, h| h[arr_keys[i]] = arr_values[i] } 
  #=> {:month=>"12", :day=>"21", :year=>"1985"}
like image 2
Cary Swoveland Avatar answered Nov 20 '22 09:11

Cary Swoveland