I understand that I can sum the properties of objects in an array in Ruby using the inject method. For example, I could sum the cash of all agents in an array using the following:
sum_of_cash = agents.inject(0) { |sum, e| sum + e.cash }
However, how can I sum only the positive or negative values of the properties, i.e. only the positive or negative cash balances, for example?
One way I can think of is doing a loop over the array and summing only if the value is positive using an if function but I’m looking for a cleaner method, if possible.
Thanks!
I thinks that something like this is a bit more elegant