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()