Re: Why nil

Hello, let's look at an example

class A
  attr_accessor :a

  def initialize(a)
    @a = a
  end

  def method1(val)
    a = val
  end

  def method2(val)
    a = a + val

You are trying to change the value of the instance variable @a I suppose?
But here you are using a local variable a that has not been defined yet.

  end

end

a = A.new(1)
a.method1(2) #=> 3

How is this 3? This will return a 2, right?

a.method2(2) #=> undefined method `+' for nil:NilClass

Changing method2 to @a = @a + val works

···

Why the second a is nil?

Another possibility is to actually use the accessors with self, like:

self.a = self.a + val

···

El 05/07/18 a las 06:26, Saurav Kothari escribió:

How is this 3? This will return a 2, right?

    a.method2(2) #=> undefined method `+' for nil:NilClass

Changing method2 to @a = @a + val works

--
Gonzalo Garramuño