了解attr_accessor类方法的自我 [英] understand self for attr_accessor class method

查看:124
本文介绍了了解attr_accessor类方法的自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test
  class << self
    attr_accessor :some

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

Test.set_some => Test
puts Test.get_some.inspect => Test nil

在上面,我可以找到self作为Test本身,但不返回some_data作为输出.

Here above I could find self as Test itself but not returning the some_data as output.

但是当我按照以下方式进行修改时,它会返回预期的输出

But while I modified in following way it returns expected output

class Test
  class << self
    attr_accessor :some

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

Test.set_some => Test
puts Test.get_some.inspect => Test some_data

有什么区别?

现在在第一个示例中,如果我将get some方法设置为

Now in the first example if I set as get some method as

Test.some = 'new_data'
puts Test.some.inspect #=> new_data
Test.set_some
puts Test.get_some.inspect => new_data

现在让我更加困惑了.

推荐答案

some = :foo使ruby认为它应该创建一个名称为some的新局部变量.如果要呼叫some=(),则必须使用显式接收器-如self.some = :foo所示.我曾经对此打赌...:-/

some = :foo makes ruby think it should create a new local variable with name some. If you want to call some=(), you have to use an explicit reciever - as in self.some = :foo. I once lost a bet on that... :-/

这篇关于了解attr_accessor类方法的自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆