简体   繁体   English

有没有更有效的方法来重构 ruby​​ 上的散列迭代?

[英]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的结构如下所示:

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".我想删除数字键,例如“1”、“3”。

And I expect to get the following container :我希望得到以下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.您可以直接通过 values 方法获取。 summary_data.values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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