Remove the error

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 }

On Tue, Aug 3, 2010 at 2:07 PM, Amir E. [email protected]
wrote:

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:ininject’
from (irb):2:in each' from (irb):2:ininject’
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:ininject’
from (irb):4:in each' from (irb):4:ininject’
from (irb):4
from :0

Amir E. wrote:

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.

array.inject { |memo,item| item != 1 ? memo+item : memo }
=> 55

array.inject(0) { |memo,item| item != 1 ? memo+item : memo }
=> 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.

Avoid expressions returning tre/false as if or nil as puts.
Two possible solutions:
1-
sum = array.inject(0) do |memo,item|
item == 3 ? (memo) : (memo + item)
end
puts “Sum = #{sum}”

2-
sum=0
puts “item sum”
array.each { |item| item == 3 ? (sum):(sum += item); printf “%4d
%6d\n”,item,sum }
puts “Sum = #{sum}”

HTH gfb

“Amir E.” [email protected] wrote in message
news:[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs