Ruby自己和put

时间:2012-03-28 16:03:20

标签: ruby

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

E.g。

    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

2 个答案:

答案 0 :(得分: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 

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

答案 1 :(得分:1)

MyClass默认继承自Object,它混合在Kernel中。

内核将puts定义为:

$stdout.puts(obj, ...)

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-puts

因此,你调用puts,它移动到self,并级联到内核。