Leo*_*Leo 13 ruby methods send
据我了解'发送'方法,这个
some_object.some_method("im an argument")
Run Code Online (Sandbox Code Playgroud)
与此相同
some_object.send :some_method, "im an argument"
Run Code Online (Sandbox Code Playgroud)
那么使用'send'方法有什么意义呢?
Int*_*idd 18
如果您事先不知道方法的名称,它可以派上用场,例如,当您进行元编程时,您可以在变量中使用方法的名称并将其传递给send方法.
它也可以用于调用私有方法,尽管大多数Ruby开发人员认为这种特殊用法并不是一种好的做法.
class Test
private
def my_private_method
puts "Yay"
end
end
t = Test.new
t.my_private_method # Error
t.send :my_private_method #Ok
Run Code Online (Sandbox Code Playgroud)
您可以使用public_send虽然只能调用公共方法.
除了Intrepidd的用例之外,当您想要在同一个接收器和/或参数上路由不同的方法时,这很方便.如果你有some_object,并且想要根据什么做什么foo,那么没有send,你需要写如下:
case foo
when blah_blah then some_object.do_this(*some_arguments)
when whatever then some_object.do_that(*some_arguments)
...
end
Run Code Online (Sandbox Code Playgroud)
但如果你有send,你可以写
next_method =
case foo
when blah_blah then :do_this
when whatever then :do_that
....
end
some_object.send(next_method, *some_arguments)
Run Code Online (Sandbox Code Playgroud)
要么
some_object.send(
case foo
when blah_blah then :do_this
when whatever then :do_that
....
end,
*some_arguments
)
Run Code Online (Sandbox Code Playgroud)
或者使用哈希,即使这样:
NextMethod = {blah_blah: :do_this, whatever: :do_that, ...}
some_object.send(NextMethod[:foo], *some_arguments)
Run Code Online (Sandbox Code Playgroud)