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]}
You can use #zip
your_array = ["12", "21", "1985"]
keys = ['month', 'day', 'year']
keys.zip(your_array).to_h
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"}
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With