【发布时间】:2013-03-24 01:24:31
【问题描述】:
我是一名新手,正在学习一些 Ruby 教程,并且对使用下面的 send 方法感到困惑。我可以看到 send 方法正在读取属性迭代器的值,但是 Ruby 文档指出 send 方法采用一个以冒号开头的方法。所以,我的困惑在于 下面的 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
【问题讨论】:
-
send也可以接受字符串,而不仅仅是符号。 “以冒号开头的方法” - 这是一个符号,它是非常基本的 ruby 概念。那么,您的问题到底是什么? -
如何将#{send(attribute)} 插入到单个属性值中?
-
attribute是属性名称,send(attribute)按名称获取值,#{send(attribute)}将其插入字符串。这与#{foo}或#{10 * 20}没有什么不同。
标签: ruby send interpolation