Ruby自己和put

dan*_*ara 3 ruby

如果self是ruby中的默认接收者,并且在实例方法定义中调用'puts',那么该对象的实例是该调用的接收者吗?

例如

    class MyClass
      attr_accessor :first_name, :last_name, :size

      # initialize, etc (name = String, size = int)

      def full_name
        fn = first_name + " " + last_name 
        # so here, it is implicitly self.first_name, self.last_name
        puts fn 
        # what happens here?  puts is in the class IO, but myClass 
        # is not in its hierarchy (or is it?)
        fn
      end
    end
Run Code Online (Sandbox Code Playgroud)

Nik*_* B. 6

当然,当前对象是此处方法调用的接收者.之所以能够工作是因为Kernel模块定义了一个puts方法并且被混合进来Object,这是每个Ruby类的隐式根类.证明:

class MyClass
  def foo 
    puts "test"
  end
end

module Kernel
  # hook `puts` method to trace the receiver
  alias_method :old_puts, :puts
  def puts(*args)
    p "puts called on %s" % self.inspect
    old_puts(*args)
  end
end

MyClass.new.foo 
Run Code Online (Sandbox Code Playgroud)

这打印puts called from #<MyClass:0x00000002399d40>,因此MyClass实例是接收器.