send
可用于调用公共方法和私有方法。
示例:
class Demo
def public_method
p "public_method"
end
private
def private_method
p "private_method"
end
end
Demo.new.send(:private_method)
Demo.new.send(:public_method)
然后使用public_send
的地点和原因?
答案 0 :(得分:8)
当您想要动态推断方法名称并调用它时,请使用public_send
,但仍然不希望出现封装问题。
换句话说,public_send
只会直接模拟方法的调用,无需解决。混合封装和元编程很有用。
示例:
class MagicBox
def say_hi
puts "Hi"
end
def say_bye
puts "Bye"
end
private
def say_secret
puts "Secret leaked, OMG!!!"
end
protected
def method_missing(method_name)
puts "I didn't learn that word yet :\\"
end
end
print "What do you want met to say? "
word = gets.strip
box = MagicBox.new
box.send("say_#{word}") # => says the secret if word=secret
box.public_send("say_#{word}") # => does not say the secret, just pretends that it does not know about it and calls method_missing.
当输入为hi
且secret
时,这是输出:
What do you want met to say? hi
=> Hi
=> Hi
What do you want met to say? secret
=> Secret leaked, OMG!!!
=> I didn't learn that word yet :\\
如您所见,send
将调用私有方法,因此会出现安全/封装问题。而public_send
只会在公共时调用该方法,否则会发生正常行为(如果被覆盖则调用method_missing
,或者引发NoMethodError
)。