Topic: Query using do..end

Hi,
  I am new to Ruby and was trying out some snippets of code. I was wondering why the following code would yield me such an error.

Code:

def addArray(intArr)
  #adds=0
 
  intArr.each do |item|
    adds = adds + item
  end
 
  #return adds
 
end

myArr=[1,2,3,4,5]
puts addArray(myArr)

Error:
arrays.rb:5:in `addArray': undefined method `+' for nil:NilClass (NoMethodError)
    from arrays.rb:4:in `each'
    from arrays.rb:4:in `addArray'
    from arrays.rb:13

However, if I remove the comment on #adds=0 it works fine. What exactly is the meaning of that error? I read somewhere that it means that the method '+' was called on nil. So does that mean that because adds was never initialized (and hence being nil) this error comes up? If that is the case, do we have to actually initialize all variables before their usage? Or is there some other way to do this?

Re: Query using do..end

Ramesh wrote:

I read somewhere that it means that the method '+' was called on nil. So does that mean that because adds was never initialized (and hence being nil) this error comes up?

Yep, that's why.

Ramesh wrote:

If that is the case, do we have to actually initialize all variables before their usage?

Yeah, there should be some value in a variable before you try to call it or try to do some process on it (like adding to it). If you don't do this Ruby doesn't know what you want the initial value to be.

Ramesh wrote:

Or is there some other way to do this?

If you're in pure ruby, you can use the inject method to do this:

arr = [1, 2, 3]
arr.inject { |a, n| a + n } # returns 6

If you're doing Rails, this is already built into the array:

arr = [1, 2, 3]
arr.sum # returns 6

Railscasts - Free Ruby on Rails Screencasts

Re: Query using do..end

Nice.. Thanks smile