this should be pretty easy for ruby wizards here. I’m having a problem with inject. This is it simply :
a = Resource.all
a.inject({ :wood => 0 }) { |res, el| res[:wood] + el.cost(1)[:wood] }
TypeError: can't convert Symbol into Integer
a is a collection and i would like to create a sum of all the wood resources of this collection. The el.cost(1)[:wood] works fine and gets an integer (resources value). So this part is correct. It seems that i have a problem with initializing my new hash with the :wood symbol and setting that value in each iteration, but i can’t really find the problem.
Any ideas ?
injectworks like this:So what you have to do in the lambda is:
res.You fail to do 2 and 3, that’s why that code doesn’t work. Try the following:
This is however a bit redundant. You can easily accumulate the integers first and then create a hash: