如何在ruby中动态创建带有参数的方法?

如何使用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
pking11 回答:如何在ruby中动态创建带有参数的方法?

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

  ['id','message','votes_count'].each do |method|
    define_method "#{method}" do |parameter|
      parameter.public_send(method)
    end
  end
本文链接:https://www.f2er.com/3159809.html

大家都在问