문제

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

다른 팁

If you don't supply an argument to the inject method, the value of sum will be the value of the first element in an array. If you want it to be 100, start your code with arr.inject(100).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top