类中的ruby常量范围<<自我阻止

时间:2015-02-19 18:10:06

标签: ruby scope private

给出像

这样的红宝石类
class Thing
  class << self
    NUM = 3

    def speak
      NUM.times { puts "Hi!" }
    end
  end
end

我无法从课堂外访问Thing::NUM。如果改为

class Thing
  NUM = 3
  class << self
    def speak
      NUM.times { puts "Hi!" }
    end
  end
end

Thing.speak仍然按预期工作,但我现在也可以访问Thing::NUM。我知道class << self成语打开了对象的单例类,但我很困惑为什么这些定义的类方法可以公开访问但是常量不是。

2 个答案:

答案 0 :(得分:4)

您必须引用正确的类:

Thing.singleton_class::NUM #=> 3

引用单例类中的常量和方法之间没有不一致:

Thing.methods.include?(:speak)                          #=> true 
Thing.singleton_class.methods.include?(:speak)          #=> false
Thing.singleton_class.instance_methods.include?(:speak) #=> true 

答案 1 :(得分:0)

  

我很困惑为什么这些定义的类方法可以公开访问,但常量不是。

是什么让你认为他们不是?

class Thing
  class << self
    NUM = 3
  end
end

Thing.singleton_class::NUM
# => 3

常量在Thing的单例类的范围内定义,因此您访问它的位置与访问Thing中定义的常量的方式完全相同。

从逻辑上考虑一下:如果您在班级BAR内定义一个常量Foo,则可以使用Foo::BAR访问它。如果您在班级BAR内定义常量Qux,则可以使用Qux::BAR访问它。如果在BAR的单例类中定义一个常量Foo,则可以使用... ???

访问它
相关问题