Attr_accessor and NoMethodError for variable

What am I missing here?

I have the following class

class Foo
  attr_accessor :x

  def initialize(x)
    @x = x
  end

  def count_down
    x -= 1
  end
end

If I then do

f = Foo.new(3)
f.count_down

I thought that I would decrement the x and then return 2, however I
get NoMethodError: undefined method '-' for nil:NilClass instead.

I thought that the attr_accessor just gave me a x and x= method,
which read and wrote to @x.

You should change your method to this:

def count_down
self.x -= 1
end

Explanation

This exception raises cause inside the method Ruby treats x like a local
variable. So after that when you run you program with expression

def count_down
x = x - 1
end

Ruby will initialize local variable x with initial nil value. And thus
you get:

x = x - 1 # => x = nil - 1 (cause initial value of x at this point is
nil).

To avoid this exception you should call x method of the current object,
i.e.

self.x = self.x - 1

or

self.x -= 1

But actually you should use instance variable instead of method inside
the object:

class Foo
attr_accessor :x

def initialize(x)
@x = x
end

def count_down
@x -= 1
end
end

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