A
Alex Fort
[Note: parts of this message were removed to make it a legal post.]
I ran across something that puzzled me today, and I thought I'd ask here and
see what you guys/girls think. I'm by no means a ruby guru, so if this is
obvious to everyone but me, I'll take the learning experience.
Here's the simple script I was testing out:
[1,2,3].inject(0) do |acc, num|
acc + num
end
It works perfectly fine when I run it. No surprises here. However, when I
add a puts call after the accumulator addition, like so:
[1,2,3].inject(0) do |acc, num|
acc + num
puts acc
end
Ruby gives me this error:
bash ~ $ ruby test.rb
0
test.rb:2: undefined method `+' for nil:NilClass (NoMethodError)
from test.rb:5:in `inject'
from test.rb:1:in `each'
from test.rb:1:in `inject'
from test.rb:1
This seems pretty strange to me, as if puts is modifying the accumulator by
resetting it to nil. Is this normal behavior? If so, I would greatly
appreciate it if someone could point me in the right direction as to why
this is the way it is. I also noticed that if I place the puts call *before*
the addition, there is no error, which also strikes me as a little odd.
Here's my ruby version (using cygwin on windows server 2003):
bash ~ $ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
Thanks,
Alex
I ran across something that puzzled me today, and I thought I'd ask here and
see what you guys/girls think. I'm by no means a ruby guru, so if this is
obvious to everyone but me, I'll take the learning experience.
Here's the simple script I was testing out:
[1,2,3].inject(0) do |acc, num|
acc + num
end
It works perfectly fine when I run it. No surprises here. However, when I
add a puts call after the accumulator addition, like so:
[1,2,3].inject(0) do |acc, num|
acc + num
puts acc
end
Ruby gives me this error:
bash ~ $ ruby test.rb
0
test.rb:2: undefined method `+' for nil:NilClass (NoMethodError)
from test.rb:5:in `inject'
from test.rb:1:in `each'
from test.rb:1:in `inject'
from test.rb:1
This seems pretty strange to me, as if puts is modifying the accumulator by
resetting it to nil. Is this normal behavior? If so, I would greatly
appreciate it if someone could point me in the right direction as to why
this is the way it is. I also noticed that if I place the puts call *before*
the addition, there is no error, which also strikes me as a little odd.
Here's my ruby version (using cygwin on windows server 2003):
bash ~ $ ruby -v
ruby 1.8.6 (2007-09-24 patchlevel 111) [i386-mswin32]
Thanks,
Alex