Ruby的send方法使用块变量插值

KMc*_*McA 5 ruby interpolation send

我是一个熟悉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
Run Code Online (Sandbox Code Playgroud)

tad*_*man 2

它不是“调用迭代器的值”,而是调用具有该名称的方法。在本例中,由于attr_accessor声明的原因,这些方法映射到属性。

称呼object.send('method_name')object.send(:method_name)相当于object.method_name一般用语。同样,send(:foo)and将调用上下文上的foo方法。foo

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