【问题标题】:Is there a more efficient way to refactor the iteration of the hash on ruby?有没有更有效的方法来重构 ruby​​ 上的哈希迭代?
【发布时间】:2020-06-19 01:28:23
【问题描述】:

我这里有一个迭代:

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

summary_data的结构如下:

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

我想删除数字键,例如“1”、“3”。

我希望得到以下container

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

有没有更有效的方法来重构上面的代码?

感谢任何帮助。

【问题讨论】:

  • @SimpleLime 哎呀,我忽略了冒号 :-)

标签: ruby hash iteration key numeric


【解决方案1】:

你可以使用Hash#values方法,像这样:

container = summary_data.values

【讨论】:

    【解决方案2】:

    如果内部哈希都具有相同的结构,则唯一有趣的信息是费用:

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

    如果您想对这些费用进行一些计算,可以将它们转换为数字:

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

    将美分用作整数可能会更好,以避免任何浮点错误:

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

    【讨论】:

    • 我建议你不要在这里使用dig,而是使用老式的h[:orders][:fees]。我们知道h[:orders] 不应该是nil。如果是,nil[:fees] 将引发异常,即我们想要的行为。相比之下,使用dig 只会返回nil,没有任何抱怨。同样,如果to_f 的接收者是nilh.dig(:orders, :fees).to_f 将返回0.0;再次,不是我们想要的。
    【解决方案3】:

    您需要一个具有所提供哈希值的数组。您可以直接通过值方法获取。 summary_data.values

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-22
      • 2012-08-12
      • 2023-01-29
      • 2014-01-02
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      相关资源
      最近更新 更多