understand self for attr_accessor class method

后端 未结 5 1883
礼貌的吻别
礼貌的吻别 2021-01-12 18:03
class Test
  class << self
    attr_accessor :some

    def set_some
      puts self.inspect
      some = \'some_data\'
    end
    def get_some
      puts sel         


        
5条回答
  •  醉话见心
    2021-01-12 19:01

    In the first example some is a local variable.

    In the second one, some is a method of self. Why? Because attr_accessor :some is the same as:

    def some= (val)
      @some = val
    end
    
    def some
      return @some
    end
    

    So, you have created the getter and setter methods for the instance variable @some (it's an instance variable of the object Test, as every class is also an object of class Class).

提交回复
热议问题