Here the array of hashes:
array = [
{:ID => "aaa", :phase => "alpha", :quantity => 80},
{:ID => "aaa", :phase => "beta", :quantity => 160}
]
I'm trying to transform the value of :phase
into a key and to assign its value taking the value of :quantity
, as follow:
array = [
{:ID => "aaa", :"alpha" => 80},
{:ID => "aaa", :"beta" => 160}
]
Thanks!
CodePudding user response:
I would do it like this:
array = [
{:ID => "aaa", :phase => "alpha", :quantity => 80},
{:ID => "aaa", :phase => "beta", :quantity => 160}
]
array.map { |hash| { :ID => hash[:ID], hash[:phase].to_sym => hash[:quantity] } }
#=> [{:ID=>"aaa", :alpha=>80}, {:ID=>"aaa", :beta=>160}]
CodePudding user response:
You can do it like this:
array.map do |hash|
new_key = hash.delete(:phase)
quantity = hash.delete(:quantity)
hash[new_key] = quantity
hash
end