Reading instance variables using self

78 Views Asked by At

I know that within class instance I should read variables' values via instance variables. But what are the consequences of reading them via self?

See example below:

class Test   attr_writer :aa
  def testing
    puts @aa
    puts self.aa <-- what are the consequences if I apply attr_reader :aa and try to read 'aa' via self.aa ? can I read other value by accident?
  end

  def self.bb
    a = self.new
    a.aa = "111"
    a.testing
  end
end

Test.bb
1

There are 1 best solutions below

3
On

In your example the variable is an instance variable to the object you just created with the self.new

Also is important to know that within the testing method self references to the object and not the class as It seems you think to. And within the bob method, since it's a class method, self references to the class.

Still, you can have instance variables within the class itself (not to be confused with class variables @@ that are accessible within all the class objects and the class itself).

Here is an example of what it can look like.

class Test

  class << self
    attr_writer :bb
  end

  def self.bb
    @bb
  end
end

Test.bb = 1
Test.bb