我很想知道send
和public_send
之间的区别。 E.g:
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
k.public_send :hello, "gentle", "readers" #=> "Hello gentle readers"
有人可以解释一下这个区别吗?
答案 0 :(得分:28)
http://apidock.com/ruby/Object/public_send
与send不同,public_send仅调用公共方法。
示例:
class Klass
private
def private_method
puts "Hello"
end
end
k = Klass.new
k.send(:private_method)
=> "Hello"
k.public_send(:private_method)
=> `public_send': private method `private_method' called for
#<Klass:0x007f5fd7159a80> (NoMethodError)