How does the injection handle the first element of an array when summing?

advertisements

I have:

arr=[40, 50, 60, 70]

arr.inject do |sum,x|
  p x
  p sum
  if x>50
    sum=sum+x
  end
  p sum
end

Why does x start on 50 and sum start on 40? My guess would be that x would iterate over 40 first. Better yet, how do I make this statement, using the inject method, return 130?


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