send method
suggest changesend passes a message to an object. It is an instance method of Object. The first argument is the method name, a string or a symbol. Symbols are preferred. Any further arguments are passed to that method.
class Hello
def hello(*args)
puts 'Hello ' + args.join(' ')
end
end
h = Hello.new
h.send :hello, 'gentle', 'readers' # prints: Hello gentle readers
# h.send(:hello, 'gentle', 'readers') #=> Here :hello is method and rest are the arguments to method.
Here is the more descriptive example
class Account
attr_accessor :name, :email, :notes, :address
def assign_values(values)
values.each_key do |k|
# same as self.name = values[:name] when k is :name
self.send("#{k}=", values[k])
end
end
end
user_info = {
name: 'Matt',
email: 'test@gms.com',
address: '132 random st.',
notes: "annoying customer"
}
account = Account.new
# If attributes increase, assigning each one manually becomes unwieldy.
#--------- Bad way --------------
account.name = user_info[:name]
account.address = user_info[:address]
account.email = user_info[:email]
account.notes = user_info[:notes]
# --------- Metaprogramming way --------------
account.assign_values(user_info) # With single line we can assign n number of attributes
puts account.inspect
send can be overridden, and it can call private methods. Prefer public_send when the method should be public. Use __send__ to call a private method, or when send itself may have been overridden.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents