Search code examples
ruby-on-railsrubyruby-on-rails-4ruby-on-rails-5

Sum all values from JSON response


I have a JSON response that looks like this:

{  
   "km"   =>"32.381",
   "tarifa"   =>25.6
},
{  
   "km"   =>"23423",
   "tarifa"   =>235.6
},
...

I want to get the sum of all tarifas. I know that I need to use map for this but am still confused on how to do it.


Solution

  • Just use Array#sum:

    array.sum { |e| e['tarifa'] }
    #=> 261.2