class MyClass
def MyFun
puts self
end
end
mine = MyClass.new
mine.MyFun # => #<MyClass:0x10a3ee670>
module、class、defはすべてスコープを変更するため、ここではdef ... end内にあるため、selfはMyClassではなくMyFunである必要があります。なぜまだMyClassに残っているのですか?
class MyClass
def MyFun
puts self
end
end
mine = MyClass.new
mine.MyFun # => #<MyClass:0x10a3ee670>
module、class、defはすべてスコープを変更するため、ここではdef ... end内にあるため、selfはMyClassではなくMyFunである必要があります。なぜまだMyClassに残っているのですか?
self
現在のコンテキストオブジェクトです。MyFun
はオブジェクトではなく、メソッドです。具体的には、MyClassのインスタンスメソッドです。したがって、の中MyFun
にself
は、を実行しているMyClassのインスタンスがありますMyFun
。
あなたの例MyFun
ではインスタンスメソッドであるためself
、実際にはのインスタンスですMyClass
。
戻ってきているのは、実際にはインスタンスリテラルです 。mine.MyFun
それがクラスリテラルである場合、それは明らかにjsutになりますMyClass
。自分でテストする
class Example
def asdf
self
end
end
Example.new.asdf.class #=> Example
の範囲self
:
クラス定義内に
self
は、常にclass constants(instance of Class)
それ自体があります(インスタンスメソッドを除く)。インスタンスメソッドの中に
self
は、それぞれのメソッドを呼び出したばかりのクラス定数のインスタンスがあります。
p RUBY_VERSION
class Foo
def self.talk
p "here SELF is-> #{self}"
end
def display
p "here SELF is-> #{self}"
end
p "here SELF is-> #{self}"
end
Foo.talk
foo = Foo.new
foo.display
class << foo
p "here SELF is-> #{self}"
end
出力:
"2.0.0"
"here SELF is-> Foo"
"here SELF is-> Foo"
"here SELF is-> #<Foo:0x1fc7fa0>"
"here SELF is-> #<Class:#<Foo:0x1fc7fa0>>"