1

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)

0

2 Answers 2

2
@horses.collect {|h| h[:odds] }.inject(:+)
Sign up to request clarification or add additional context in comments.

2 Comments

Fixed. Many thanks... will mark as answered in a few minutes when it lets me.
Might be nice to also elaborate on why the OP's attempt doesn't work.
1

You can use a block with inject if you need to unpack the elements that you're iterating over:

@horses.inject(0) { |m, h| m + h[:odds] }

When you say this:

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

You're trying to use a symbol, :odds, as an index for an Array; Array indexes are integers and there's no way for an Array to convert a symbol to an integer so you get an can't convert Symbol into Integer error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.