I have a hash :
hash = {"str1"=>2, "str2"=>3, "str3"=>7}
I want to calculate the percentage of each element in the hash so I can get one like this :
{"str1"=>16.66% , "str2"=>25.00%, "str3"=>58.33%}
Any idea about that? Thanks
You can use Enumerable#each_with_object
:
sum = a.values.inject(0, :+) # or simply a.values.sum if you're on Ruby 2.4+
#=> 12
a.each_with_object({}) { |(k, v), hash| hash[k] = v * 100.0 / sum }
#=> {"str1"=>16.666666666666668, "str2"=>25.0, "str3"=>58.333333333333336}
To have it with %
:
a.each_with_object({}) { |(k, v), hash| hash[k] = "#{(v * 100.0 / sum).round(2)}%" }
#=> {"str1"=>"16.67%", "str2"=>"25.0%", "str3"=>"58.33%"}