gpt4 book ai didi

Ruby 的带有 block 变量插值的发送方法

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

我是一个正在学习一些 Ruby 教程的新手,并且对下面的 send 方法的使用感到困惑。我可以看到 send 方法正在读取属性迭代器的值,但 Ruby 文档指出 send 方法采用一个以冒号为前缀的方法。所以,我的困惑在于下面的发送方法如何插入被迭代的属性变量。

module FormatAttributes
def formats(*attributes)
@format_attribute = attributes
end

def format_attributes
@format_attributes
end
end

module Formatter
def display
self.class.format_attributes.each do |attribute|
puts "[#{attribute.to_s.upcase}] #{send(attribute)}"
end
end
end

class Resume
extend FormatAttributes
include Formatter
attr_accessor :name, :phone_number, :email, :experience
formats :name, :phone_number, :email, :experience
end

最佳答案

这不是“调用迭代器的值”,而是调用具有该名称的方法。在这种情况下,由于 attr_accessor 声明,这些方法映射到属性。

调用 object.send('method_name')object.send(:method_name) 在一般意义上等同于 object.method_name .同样,send(:foo)foo 将在上下文中调用方法 foo

由于 module 声明了一个稍后与 include 混合的方法,因此在模块中调用 send 具有调用 a 的效果Resume 类实例上的方法。

关于Ruby 的带有 block 变量插值的发送方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769385/

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