使用“发送"消息有什么意义?而不是正常的方法调用? [英] What is the point of using "send" instead of a normal method call?

查看:91
本文介绍了使用“发送"消息有什么意义?而不是正常的方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,发送"方法

some_object.some_method("im an argument")

与此相同

some_object.send :some_method, "im an argument"

那么使用发送"方法有什么意义呢?

So what is the point using 'send' method?

推荐答案

如果您事先不知道方法的名称,它可能会派上用场,例如,在进行元编程时,您可以使用该名称方法中的变量,然后将其传递给send方法.

It can come in handy if you don't know in advance the name of the method, when you're doing metaprogramming for example, you can have the name of the method in a variable and pass it to the send method.

它也可以用于调用私有方法,尽管大多数Ruby开发人员都不认为这种特殊用法是一种好习惯.

It can also be used to call private methods, although this particular usage is not considered to be a good practice by most Ruby developers.

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

尽管只能调用公共方法,但可以使用public_send.

You can use public_send though to only be able to call public methods.

这篇关于使用“发送"消息有什么意义?而不是正常的方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆