Ruby将字符串转换为方法名称

ver*_*ure 36 ruby methods

我在ruby文件中定义了两个方法.

def is_mandatory(string)
      puts xyz
end
def is_alphabets(string)
      puts abc 
end 
Run Code Online (Sandbox Code Playgroud)

包含方法名称的数组.

    methods = ["is_mandatory", "is_alphabets"]
Run Code Online (Sandbox Code Playgroud)

当我做以下

    methods.each do |method| puts method.concat("(\"abc\")") end 
Run Code Online (Sandbox Code Playgroud)

它只显示is_mandatory("abc")is_alphabets("abc")而不是实际调用该方法.

如何将字符串转换为方法名称?任何帮助是极大的赞赏.

干杯!!

Cho*_*ett 55

最好的方法可能是:

methods.each { |methodName| send(methodName, 'abc') }
Run Code Online (Sandbox Code Playgroud)

请参见对象#send

  • 然后你想要的东西:`obj = OwningClass.new; methods.each {| meth | obj.send(meth,'abc')}` (2认同)
  • 或者如果我们谈论类方法,那么 `methods.each{ |method| Class.send(meth, 参数) }` (2认同)

Aur*_*ril 13

尝试使用"发送".

methods.each do |method| 
  self.send(method, "abc")
end 
Run Code Online (Sandbox Code Playgroud)