【问题标题】:How to dynamically create methods with parameter in ruby?如何在ruby中动态创建带参数的方法?
【发布时间】:2019-11-05 12:04:48
【问题描述】:

如何使用 ruby​​ 元编程动态创建这样的方法?

class CommentBridge < Bridge

  def id(comment)
    comment.id
  end

  def message(comment)
    comment.message
  end

  def votes_count(comment)
    comment.votes_count
  end

end

我试过了,但它不起作用。

  ['id', 'message', 'votes_count'].each do |method|
    define_method "#{method}" do |parameter|
      method(parameter.method)
    end
  end

【问题讨论】:

  • 怎么不工作了?抛出某种错误?它与混合字符串和方法有关吗? (.each do |method| 然后是method(...))?
  • 您可以简单地将这些方法委托给comment
  • ArgumentError(参数数量错误(给定 0,预期为 1))@SimpleLime

标签: ruby-on-rails ruby metaprogramming


【解决方案1】:

您应该使用public_send 根据名称调用方法:

  ['id', 'message', 'votes_count'].each do |method|
    define_method "#{method}" do |parameter|
      parameter.public_send(method)
    end
  end

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 2016-11-09
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2021-12-05
    • 2019-09-09
    相关资源
    最近更新 更多