Class variable using attr_accessor inside class << self

Can someone explain why self.foo = works outside of the <self class, whereas foo = doesn't work in the <class on its own.

class A
  class << self
    attr_accessor :foo
    foo = 'foo'
  end
end

p A.foo # => "nil"

class A
  class << self
    attr_accessor :foo
  end
  self.foo = 'foo'
end

p A.foo # => "foo"

      

It is not a question of When to use "I" in Ruby

To be clear, I am not asking when to use myself. I am asking why I cannot set a class variable inside the <self 'class, but I can outside of it.

+3


source share


1 answer


your second example is not a class variable, it is a class instance variable for that class, the proof is that if you inherit this you get nil

class A
  class << self
    attr_accessor :foo
  end
  self.foo = 'foo'
end

class B < A
end

B.foo # => nil

      



So, if you want to add a class variable to class << self

, you can use@@

class A

  class << self
  @@foo = :foo
    def foo
      @@foo
    end
  end
end

      

+2


source







All Articles