Remove the error

  • Thread starter Amir Ebrahimifard
  • Start date
A

Amir Ebrahimifard

Hi
Why these codes result error ?

1-
array = [*1..10]
sum = array.inject { |memo,item| memo+item if item !=3 }

2-
array = [*1..10]
sum = array.inject { |memo,item| puts memo+item }
 
B

brabuhr

Why these codes result error ?

2-
array = [*1..10]
sum = array.inject { |memo,item| puts memo+item }

irb(main):001:0> array = [*1..10]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):002:0> sum = array.inject { |memo,item| puts memo+item }
3
NoMethodError: undefined method `+' for nil:NilClass
from (irb):2
from (irb):2:in `inject'
from (irb):2:in `each'
from (irb):2:in `inject'
from (irb):2
from :0

The method 'puts' always returns 'nil':

irb(main):003:0> sum = array.inject { |memo,item| puts "#{memo}\t#{item}" }
1 2
3
4
5
6
7
8
9
10
=> nil

irb(main):004:0> sum = array.inject { |memo,item| puts
"#{memo}\t#{item}\t#{memo + item}" }
1 2 3
NoMethodError: undefined method `+' for nil:NilClass
from (irb):4
from (irb):4:in `inject'
from (irb):4:in `each'
from (irb):4:in `inject'
from (irb):4
from :0
 
B

Brian Candler

Amir said:
Hi
Why these codes result error ?

1-
array = [*1..10]
sum = array.inject { |memo,item| memo+item if item !=3 }

sum = array.inject(0) { |memo,item| item != 3 ? memo+item : memo }

Note a subtlety here: if you omit the (0) argument then the initial memo
is always set to the first item, so you wouldn't be able to skip it.
=> 54
2-
array = [*1..10]
sum = array.inject { |memo,item| puts memo+item }

sum = array.inject { |memo,item| puts memo,item; memo+item }

In both cases, you need to ensure that the last expression evaluated by
the block is the value you want for the 'memo' in the next iteration.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,375
Latest member
FelishaCma

Latest Threads

Top