Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's send method with block variable interpolation

I'm a newb working through some Ruby tutorials and am stumped on the use of the send method below. I can see the send method is reading the value of the attribute iterator over, but the Ruby documentation states the send method takes a method prepended with a colon. So, my confusion lies in how the send method below is interpolating the attribute variable being iterated over.

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
like image 238
KMcA Avatar asked Nov 03 '22 01:11

KMcA


1 Answers

It's not "invoking the value of the iterator", but instead calling a method with that name. In this case because of the attr_accessor declaration, these methods map to properties.

Calling object.send('method_name') or object.send(:method_name) are equivalent to object.method_name in general terms. Likewise, send(:foo) and foo will call the method foo on the context.

Since the module declare a method that is later mixed in with an include, calling send in the module has the effect of calling a method on an instance of the Resume class.

like image 90
tadman Avatar answered Nov 15 '22 05:11

tadman