【问题标题】:Call a method whose name is contained within a string? [duplicate]调用名称包含在字符串中的方法? [复制]
【发布时间】:2012-03-20 02:04:22
【问题描述】:

可能重复:
How to turn a string into a method call?

使用 Ruby 1.9,如何调用包含在字符串中的方法。我尝试了以下方法:

self.'method_name'

基本上,我试图做的是基于基于当前方法名称的通用命名约定调用方法。我希望能够打电话

self."#{__method__}_path"

并让我在方法search 中执行代码,就像我正在调用一样

self.search_path

【问题讨论】:

    标签: ruby ruby-1.9


    【解决方案1】:

    你看过send吗?

    类似:

    ACTIONS = %w[foo bar]
    
    def execute(action)
          return send("do_#{action}") if ACTIONS.include?(action)
          raise "Unexpected action"
    end
    

    参考:http://ruby-doc.org/core-1.9.3/Object.html#method-i-send

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2017-07-16
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 2016-10-04
      • 1970-01-01
      相关资源
      最近更新 更多