gpt4 book ai didi

Ruby 自身和 puts

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:35 27 4
gpt4 key购买 nike

如果 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

最佳答案

绝对的,当前对象就是这里方法调用的接收者。之所以可行,是因为 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实例是接收者。

关于Ruby 自身和 puts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9911445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com