我知道还有其他关于语法的问题class << self
。尽管如此,我还没有发现这些答案足够清楚。我有 Java/C#、C 的背景,所以 Ruby 对我来说有点奇怪。我读到的是class << self
指单例类。我觉得这有点复杂,所以我想了解操作员<<
在这种情况下做了什么,以及两端都有什么可能。我尝试编写一个简单的代码来帮助我理解这种语法(我的问题在代码中):
class Self
def Self.selfTest
end
def onSelf
class << Self #I know this might be strange.
self
end
end
def onself
class << self
self
end
end
end
s = Self.new
onSelf = s.onSelf
onself = s.onself
#Here, i wanna know what kind of references are returned.
puts "onSelf responds to onSelf:#{onSelf.respond_to?(:onSelf)}"
puts "onSelf responds to selfTest:#{onSelf.respond_to?(:selfTest)}"
puts "onself responds to onSelf:#{onself.respond_to?(:onSelf)}"
puts "onself responds to selfTest:#{onself.respond_to?(:selfTest)}"
#Output:
#onSelf responds to onSelf:false
#onSelf responds to selfTest:false
#onself responds to onSelf:false
#onself responds to selfTest:true
#So, i conclude that the second one is a reference to a class. What is the first one???????
puts onSelf
puts onself
#Output
#<Class:Self>
#<Class:#<Self:0x007f93640509e8>>
#What does this outputs mean???????
def onSelf.SelfMet
puts 'This is a method defined on base class'
end
def onself.selfMet
puts 'This is a method defined on metaclass'
end
puts "Does Self Class respond to SelfMet? : #{Self.respond_to?(:SelfMet)}"
puts "Does Self Class respond to selfMet? : #{Self.respond_to?(:selfMet)}"
puts "Does Self instance respond to SelfMet? : #{s.respond_to?(:SelfMet)}"
puts "Does Self instance respond to selfMet? : #{s.respond_to?(:selfMet)}"
#Output
#Does Self Class respond to SelfMet? : false
#Does Self Class respond to selfMet? : false
#Does Self instance respond to SelfMet? : false
#Does Self instance respond to selfMet? : false
#Why won't they respond to defined methods????
谢谢
更新: 非常感谢大家。我已经阅读和测试了很多,所以会留下一些注意事项。我将其留作将来参考,因此,如果我错了,我希望 Ruby 专家能纠正我。我意识到 class << Self 指的是 Self 单例类。因此,惯用类 << abcd 启动 abcd 单例类上下文。我还意识到类单例类的层次结构与对象单例类不同。类单例类的层次结构遵循层次结构中的所有单例类。在这种情况下:
单例自身->单例对象->单例基本对象->类->模块->对象->内核->基本对象
对象单例类位于不同的层次结构中:
对象单例->自我->对象->内核->基本对象
这解释了这个输出。