5

The following code sets a class variable in the class C from a class method, and shows that it is accessible from an instance method:

class C
  def self.set_a
    @@a = 1
  end

  def get_a
    @@a
  end
end

C.set_a
C.new.get_a #=> 1

If I replace @@a in the class method set_a with @a, so that it creates a class instance variable instead of a class variable, can I still access it from within the instance method get_a?

2
  • I assume you know that you can't write def get_a; @a; end, as c = C.new; c.get_a would return the value of c's instance_variable @a. You therefore will need to employ two methods within get_a to obtain the value of the class instance variable @a. The first to obtain c's class; the second, invoked on c's class, to obtain the value of the variable. Commented Nov 28, 2018 at 21:34
  • 1
    Instance variables belong to instances. That's why they are called instance variables. C and C.new are two completely different objects that have absolutely northing to do with each other. The whole point of instance variables is that one object cannot access another object's instance variables, unless that object explicitly exposes them in some manner. Commented Nov 29, 2018 at 9:39

1 Answer 1

4

I don't think you can reference it directly. Class is an object and instance variables are private/internal to the object. You can access it either using instance_variable_get on the class or by wrapping it in a getter method.

In Rails you can use class_variable macro that facilitates setting and accessing class-level variables.

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

4 Comments

What do you mean you can't reference it directly? Is not instance_variable_get a perfectly good, garden-variety method? I think you should say "yes, use instance_variable_get".
I mean that you cannot reference them using @@var or @var form, you need to use a method to access it.
Yes, I realize that, but the OP merely says, "...can I still access it from within the instance method get_a?". There's no mention of not using a method. Also, the mention of an accessor is somewhat irrelevant as it would seem that the OP only wants to change get_a and even if there were an accessor, you'd still be using a method in get_a to access it. This is of course a minor points.
@CarySwoveland in that sense almost all variables are accessible from everywhere (the only exception being local variables). With class_eval instance_eval and send you can bypass any scope restrictions, even if there isn't a standard interface in place like instance_variable_get

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.