Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

Error inside inject method

I am trying to learn the inject method. I thought I will just print elements as it calculates. But in the following code when I comment print b statement it works fine. But when I uncomment it, error occurs. What does that mean? The error occurs for a+b statement which is at line number 4 mentioned in the error.

list = *(1..10)

list.inject(0) do |a, b|
  a + b
  print b
end

Error:

undefined method `+' for nil:NilClass (NoMethodError)

Upvotes: 1

Views: 53

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

Solution:

list.inject(0) do |a, b|
  print b
  a + b
end
#=> 12345678910=> 55

Explanation:

inject returns the cumulated value from previous iteration (a).

When you are printing b it is the return value of the iteration, thus a is nil. To solve it move the printing above, so that a is still the return value of the iteration.

Upvotes: 4

Related Questions