【问题标题】:How to call a method with question mark via send in ruby如何通过发送红宝石调用带问号的方法
【发布时间】:2019-11-15 04:26:26
【问题描述】:

我有为符号列表生成的方法。其中一种方法在其定义中包括一个问号。我想用一个持有该符号的变量来调用这样的方法。

假设我们为 :check_element 符号生成了一个方法,对应的方法签名如下所示。

class A
    def check_element?

    end
end

现在我有一个变量flag = :check_element,我无法调用像A.send(flag) 这样的方法

A.send((flag.to_s + '?').to_sym) 有效。

我正在考虑是否有更好的方法来实现这一点。

【问题讨论】:

  • 我猜总是有 "#{flag}?":"#{flag}?" (如果你真的想要一个符号,即使 send 对字符串很满意)。
  • @thebenman : 你不能简单地设置flag = :check_element? 吗?
  • “假设我们为 :check_element 符号生成一个方法,并且相应的方法签名看起来像” - 为什么为:check_element 生成的方法名称会以@987654330 结尾@。问号从何而来?
  • 顺便说一句,check_element? 是一个 instance 方法——你不能通过A.send(...)调用它

标签: ruby-on-rails ruby metaprogramming


【解决方案1】:

不需要将方法名称参数转换为符号,因为send 也接受字符串。这允许将您的示例简化为

A.send(flag.to_s + '?')

这可以使用字符串插值来简化

A.send("#{flag}?")

【讨论】:

  • 为了语义清晰,请始终建议使用public_send 而不是send
猜你喜欢
  • 1970-01-01
  • 2017-06-06
  • 2014-12-05
  • 2011-04-02
  • 2019-06-18
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
相关资源
最近更新 更多