ruby on rails - Get and add values from JSON -


here 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 values of each , add them together. long , incorrect way each value , add them so:

first_number = json["graph"][0]["1"] second_number = json["graph"][0]["2"] 

how can simplify total count?

if need sum of values...

json['graph'][0].values.inject{|sum,val| sum+val} 

if using rails, have option use sum method instead:

json['graph'][0].values.sum 

inject takes given block , executes block once every element in array. val current value being evaluated, , sum value last returned block. thus, if add 2 every time block runs, , return result, sum of values @ end of execution.

you can see documentation here: http://apidock.com/ruby/enumerable/inject


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -