user200783
user200783

Reputation: 14348

In Ruby, can I access a class instance variable from within an instance method?

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?

Upvotes: 4

Views: 2643

Answers (1)

mrzasa
mrzasa

Reputation: 23307

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.

Upvotes: 4

Related Questions