構文について他にも質問があることは承知しています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 の専門家が私が間違っている場合は修正してくれることを願っています。クラス << Self が Self シングルトン クラスを参照していることに気付きました。したがって、慣用的なクラス << abcd は、abcd シングルトン クラス コンテキストを開始します。また、クラスのシングルトン クラスの階層は、オブジェクトのシングルトン クラスとは異なることに気付きました。クラス シングルトン クラスの階層は、階層上のすべてのシングルトン クラスに従います。この場合:
singleton Self->singleton Object->Singleton basicobject ->class->module->object->kernel->basicObject
オブジェクト シングルトン クラスは、別の種類の階層にあります。
オブジェクト singleton->Self->Object->kernel->basicObject
これは、この出力を説明しています。