understand self for attr_accessor class method

后端 未结 5 1843
礼貌的吻别
礼貌的吻别 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:02

    in the first method

    def set_some
      puts self.inspect
      some = 'some_data'
    end
    

    some is a local variable.. its not the same as @some that is a instance variable (in this case a class instance variable) so the value disappears when the method ends.

    if you want to call the setter method some or set @some to something then do this

    @some = 'some_data'
    

    or

    self.some = 'some_data'
    

    in the second method

    def get_some
      puts self.inspect
      self.some
    end
    

    your calling the method some. which returns the instace variable @some.. and since at this point @some has no value.. returns nil..

提交回复
热议问题