From: Amir Ebrahimifard on
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 }
--
Posted via http://www.ruby-forum.com/.

From: brabuhr on
On Tue, Aug 3, 2010 at 2:07 PM, Amir Ebrahimifard <amiref(a)ymail.com> 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: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

From: Brian Candler on
Amir Ebrahimifard 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.
--
Posted via http://www.ruby-forum.com/.

From: GianFranco Bozzetti on
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 Ebrahimifard" <amiref(a)ymail.com> wrote in message
news:224ee235f7c68ed448aa8d66d540fbc8(a)ruby-forum.com...
> 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 }
> --
> Posted via http://www.ruby-forum.com/.
>


 | 
Pages: 1
Prev: Inject problem
Next: documenting string