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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With