Ruby convert string to method name

前端 未结 4 1164
醉话见心
醉话见心 2020-12-28 12:43

I have two methods defined in my ruby file.

def is_mandatory(string)
      puts xyz
end
def is_alphabets(string)
      puts abc 
end 

An

相关标签:
4条回答
  • 2020-12-28 13:14

    All previous solutions with send are fine but it is recommended to use public_send instead (otherwise you can be calling private methods).

    Example:

    'string'.public_send(:size)
    => 6
    
    0 讨论(0)
  • 2020-12-28 13:29

    You can also add hash to send parameters to the method.

    send("method_name", "abc", {add more parameters in this hash})
    
    0 讨论(0)
  • 2020-12-28 13:30

    Try using "send".

    methods.each do |method| 
      self.send(method, "abc")
    end 
    
    0 讨论(0)
  • 2020-12-28 13:34

    Best way is probably:

    methods.each { |methodName| send(methodName, 'abc') }
    

    See Object#send

    0 讨论(0)
提交回复
热议问题