如果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
答案 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,并级联到内核。