简体   繁体   中英

Is there a more efficient way to refactor the iteration of the hash on ruby?

I have a iteration here:

container = []
summary_data.each do |_index, data|
  container << data
end

The structure of the summary_data is listed below:

summary_data = {
  "1" => { orders: { fees: '25.00' } },
  "3" => { orders: { fees: '30.00' } },
  "6" => { orders: { fees: '45.00' } }
}

I want to remove the numeric key, eg, "1", "3".

And I expect to get the following container :

[
  {
    "orders": {
      "fees": "25.00"
    }
  },
  {
    "orders": {
      "fees": "30.00"
    }
  },
  {
    "orders": {
      "fees": "45.00"
    }
  }
]

Is there a more efficient way to refactor the code above?

Appreciate for any help.

您可以使用Hash#values方法,如下所示:

container = summary_data.values

If the inner hashes all have the same structure, the only interesting information are the fees:

summary_data.values.map{|h| h[:orders][:fees] }
# => ["25.00", "30.00", "45.00"]

If you want to do some calculations with those fees, you could convert them to numbers:

summary_data.values.map{|h| h[:orders][:fees].to_f }
# => [25.0, 30.0, 45.0]

It might be even better to work with cents as integers to avoid any floating point error:

summary_data.values.map{|h| (h[:orders][:fees].to_f * 100).round }
=> [2500, 3000, 4500]

You need an array having values of provided hash. You can get by values method directly. summary_data.values

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