Reputation: 171
Here is my Hash:
{"graph"=>[{"1"=>16, "2"=>44, "3"=>53, "4"=>53, "5"=>80, "6"=>71, "7"=>63, "8"=>54, "9"=>53, "10"=>44, "11"=>76, "12"=>82, "13"=>66, "14"=>59, "15"=>64, "16"=>39, "17"=>19, "18"=>14, "19"=>5, "20"=>6, "21"=>5, "22"=>7, "23"=>6, "24"=>7}]}
I'm trying to get the values of each and add them together. The long and incorrect way would be to get each value and add them together like so:
first_number = json["graph"][0]["1"]
second_number = json["graph"][0]["2"]
How can I simplify this to get that total count?
Upvotes: 0
Views: 169
Reputation: 16092
If all you need is the sum of those values...
json['graph'][0].values.inject{|sum,val| sum+val}
If you are using rails, you have the option to use the sum
method instead:
json['graph'][0].values.sum
inject
takes a given block and executes the block once for every element in the Array. val
is the current value being evaluated, and sum
is the value that was last returned from the block. Thus, if you add the two every time the block runs, and return the result, you will get a sum of your values at the end of execution.
You can see the documentation here: http://apidock.com/ruby/Enumerable/inject
Upvotes: 6