对于send方法,ruby doc中如下描述
Invokes the method identified by symbol , passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj .
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
但对于如下代码,利用send可以调用private方法。
class MyClass
private
def say_hello(name)
puts "Let's go back to my place, #{name}."
end
end
my_object = MyClass.new
my_object.send :say_hello, "world"
#Let's go back to my place, world.
Now, honestly, this strikes me as odd. Conceptually, I don't see why send
should function differently from an ordinary method call with respect to access control.
The rubydoc for send
says nothing of this, and there is some debate on the mailinglist as to whether Ruby 1.9's send
will maintain this behavior.
But for now this can be very useful if you disagree with a class designer's method access choices.