0
class MyClass
  def MyFun
    puts self
  end
end

mine = MyClass.new
mine.MyFun   # => #<MyClass:0x10a3ee670>

由于模块、类、def 都改变了范围,这里 self 应该是 MyFun 而不是 MyClass,因为它在 def...end 中。为什么它仍然保留在 MyClass 中?

4

3 回答 3

0

self是当前上下文对象。MyFun不是一个对象,而是一个方法——具体来说,它是 MyClass 的一个实例方法。所以在里面MyFunself将是正在执行的 MyClass 的实例MyFun

于 2013-03-26T21:08:44.857 回答
0

范围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>>"
于 2013-03-27T04:47:51.173 回答
0

在您的示例MyFun中是一个实例方法,self实际上也是一个MyClass.

返回的东西 mine.MyFun实际上是实例文字。如果它是一个类文字,那将是 jsut plainly MyClass。自己测试一下

class Example
  def asdf
    self
  end
end

Example.new.asdf.class #=> Example
于 2013-03-26T21:11:41.897 回答