调用名称包含在字符串中的方法?

时间:2012-03-20 02:04:22

标签: ruby ruby-1.9

  

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

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

self.'method_name'

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

self."#{__method__}_path"

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

一样
self.search_path

1 个答案:

答案 0 :(得分:3)

你看过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

相关问题