Search code examples
rubyinstanceinstance-variablesinstance-methods

calling ruby instance method


class R
  def initialize(number)
    @number = number
  end

  attr_accessor :number
end

r = R.new(3)

r.number => 3
r.@number => syntax error
r.(@number) => undefined method call

Why can't the instance variable invoked this way?

As far as I know thanks to the attr_accessor

def number
  @number
end

So r.number method should return self.@number which is r.@number

What did I miss?


Solution

  • r.number method should return self.@number which is r.@number

    No. Nowhere in the definition of the number method says self.@number. It says: @number. It should return the value of @number.

    @number is an instance variable, not a method. You cannot call it (like that or in any other way), you can only refer to it from an appropriate scope.