简体   繁体   中英

How to insert key/value pair where the key is the value of another pair? Array of hashes Ruby

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

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}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM