Search code examples
rubyarrayshashadditioninject

How to add up specific hash attributes within an array


I want to add up specific attributes from an array of hashes... here's an example array:

@horses = [
        {name: "Runner1", odds: 4.00},
        {name: "Runner2", odds: 20.00},
        {name: "Runner3", odds: 4.00}
        ]

And am trying this method:

@total_odds = horses[:odds].inject(:+)

But I'm getting an error: [ ]': can't convert Symbol into Integer

What am I doing wrong? Many thanks in advance (have just started learning)


Solution

  • @horses.collect {|h| h[:odds] }.inject(:+)