Inject is using the first element of the array as a starting sum and executes the block starting from the second element. You can pass a starting sum to inject using inject(0) do ..end
.
It will then start with sum
equal to 0 and execute the block from first the element. Also note that sum
is being assigned to the value of the executed block, so your code won't work at all. It should be:
arr=[40, 50, 60, 70]
arr.inject do |sum,x|
x > 50 ? sum+x : sum
end
However I would write it slightly simpler:
arr=[40, 50, 60, 70]
arr.select {|v| v > 50}.reduce(0, &:+)
If you are using Active Support (from Rails), you can simply do:
arr.select {|v| v > 50}.sum