Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby';带块变量插值的s-send方法_Ruby_Send_Interpolation - Fatal编程技术网

Ruby';带块变量插值的s-send方法

Ruby';带块变量插值的s-send方法,ruby,send,interpolation,Ruby,Send,Interpolation,我是一个新手,正在学习一些Ruby教程,对于下面的send方法的使用感到困惑。我可以看到send方法正在读取属性迭代器的值,但是Ruby文档说明send方法使用冒号前面的方法。因此,我的困惑在于下面的send方法是如何插值正在迭代的属性变量的 module FormatAttributes def formats(*attributes) @format_attribute = attributes end def format_attributes @format

我是一个新手,正在学习一些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

以下是代码的简化版本,用于向您提供所发生的事情:

def show
 p "hi"
end

x = "show"
y = :show

"#{send(y)}"   #=> "hi"
"#{send(x)}"   #=> "hi"
它不是“调用迭代器的值”,而是调用具有该名称的方法。在这种情况下,由于
attr\u访问器
声明,这些方法映射到属性

调用
object.send('method\u name')
object.send(:method\u name)
一般等同于
object.method\u name
。同样,
send(:foo)
foo
将在上下文中调用方法
foo


由于
模块
声明了一个后来与
包含
混合的方法,因此在模块中调用
发送
会对Resume类的实例调用一个方法。

发送
也可以使用字符串,而不仅仅是符号。“前面有冒号的方法”-这是一个符号,它是非常基本的ruby概念。那么,您的问题是什么?如何将{send(attribute)}插入到单个属性值中?
attribute
是属性名,
send(attribute)
按名称获取值,
{send(attribute)}
将其插入到字符串中。它和,比如说,
{foo}
或者
{10*20}
没有什么不同;“#{send(x)}”
也可以。我认为在本例中,字符串值被强制转换为符号,因此OP的一部分答案可能是“Ruby提供了内置强制,这允许发布的代码工作”@NeilSlater我试图向他展示send是如何工作的。就这样。我的代码有什么错误吗?纠正我。我没听懂,你的密码没问题。我只是想把它和我在OP中注意到的东西联系起来(“takes a method prepend with a冒号”)@tadam,谢谢!作为新手,我并不认为attr_访问器正在将属性转换为方法。现在完全有意义了。
attr\u reader
创建一个读取方法(getter),
attr\u writer
创建一个写入方法(setter),而
attr\u accessor
同时创建这两个方法。