0
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?

1
  • 1
    here sawa answer is perfect one way you can get the instance variable @number value r.instance_variable_get(:@number) by this way Commented Apr 8, 2016 at 9:19

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any other conventional way to get into the scope besides the getter method?
@SzilardMagyar instance_eval. But that defeats OOP, and is also slow. If you can use a different syntax, you can use instance_variable_get, as Rajarshi Das notes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.