带散列的数组 - 如何舍入(2)值

时间:2016-06-07 10:50:12

标签: ruby

我多年来一直在努力。我正在尝试使用哈希值对数组进行舍入。

[
  {
    :email => "user_01@yorlook.com",
    :amount => 129.22500000000002
  },
  {
    :email => "user_02@yorlook.com",
    :amount => 112.67500000000001
  }
]

我需要一种方法让它看起来像这样:

[
  {
    :email => "user_01@yorlook.com",
    :amount => 129.23
  },
  {
    :email => "user_02@yorlook.com",
    :amount => 112.68
  }
]

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

假设arr始终包含Hash,密钥amountFloat(如示例所示)。

arr.each { |hash|
 hash[:amount] = hash[:amount].round(2)
}
#=> [{:email=>"user_01@yorlook.com", :amount=>129.23}, {:email=>"user_02@yorlook.com", :amount=>112.68}]