6

I'm trying to count the occurrences of elements in an array and save it in a hash. I'd like to use the inject function. I have this code:

a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1}

I don't understand why I get the following error:

TypeError: can't convert String into Integer
    from (irb):47:in `[]'
    from (irb):47:in `block in irb_binding'
    from (irb):47:in `each'
    from (irb):47:in `inject'

Also, I don't know how to fix it.

2

1 Answer 1

10

inject calls your block with two parameters, memo and current element. It then takes return value of the block and replaces memo with it. Your block returns integers. So, after first iteratation, your memo is not a hash anymore, it's an integer. And integers don't accept strings in their indexers.

Fix is easy, just return hash from the block.

a = ["the","the","a", "it", "it", "it"]
a.inject(Hash.new(0)) {|hash,word| hash[word] += 1; hash }

You may prefer each_with_object because it doesn't replace memo. Note that each_with_object accepts parameters in reverse (element first, memo second).

a.each_with_object(Hash.new(0)) {|word, hash| hash[word] += 1}
Sign up to request clarification or add additional context in comments.

6 Comments

probably good answer, but for self learning I would ask you - each_with_object accepts parameters in reverse (element first, memo second). So how this reverse orders helps, which inject doesn't. Can I have more flavor on this?
It's not the order that helps. It's that each_with_object doesn't replace memo.
@RubyLovely the order has nothing to do with it, it's just how each_with_object works.
make sense now from the line each_with_object doesn't replace memo..forgot for a while..Thanks Buddy :)
@RubyLovely inject does not return 1; hash[word] += 1 does.
|

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.