send() 方法
send()
用于将消息传递给 object
。send()
是 Object
类的实例方法。send()
中的第一个参数是你要发送给对象的消息 - 即方法的名称。它可以是 string
或 symbol
,但符号是首选。那些需要传递方法的参数,那些将是 send()
中的剩余参数。
class Hello
def hello(*args)
puts 'Hello ' + args.join(' ')
end
end
h = Hello.new
h.send :hello, 'gentle', 'readers' #=> "Hello gentle readers"
# h.send(:hello, 'gentle', 'readers') #=> Here :hello is method and rest are the arguments to method.
这是更具描述性的例子
class Account
attr_accessor :name, :email, :notes, :address
def assign_values(values)
values.each_key do |k, v|
# How send method would look a like
# self.name = value[k]
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 gets increase then we would messup the code
#--------- Bad way --------------
account.name = user_info[:name]
account.address = user_info[:address]
account.email = user_info[:email]
account.notes = user_info[:notes]
# --------- Meta Programing way --------------
account.assign_values(user_info) # With single line we can assign n number of attributes
puts account.inspect
注意:不再推荐 send()
本身。使用能够调用私有方法的 __send__()
,或者(推荐)public_send()