joeyk16 joeyk16 - 6 months ago 7
Ruby Question

Array with hashes - How to round(2) the values

I have been trying for ages. I am trying to round an array with hashes.

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


I need a method to make it look like this:

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


Thanks for your help in advance!

Answer

Assuming arr always contains Hash with key amount which is a Float (as in example).

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