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 array containing the names of the methods.

    methods = ["is_mandatory", "is_alphabets"]

When I do the following

    methods.each do |method| puts method.concat("(\"abc\")") end 

It just displays, is_mandatory("abc") is_alphabets("abc") rather than actually calling the method.

How can i convert the string to method name? Any help is greatly appreciated.

Cheers!!

1
  • 4
    On a side note, the Ruby way of doing is_* methods is by using a question mark rather than the prefix "is", i.e. mandatory? and alphabets?. Commented Oct 24, 2012 at 9:42

4 Answers 4

63

Best way is probably:

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

See Object#send

Sign up to request clarification or add additional context in comments.

3 Comments

If these methods belong to some class?
Then you want something like: obj = OwningClass.new; methods.each { |meth| obj.send(meth, 'abc') }
or if we're talking about class methods, then methods.each{ |method| Class.send(meth, argument) }
15

Try using "send".

methods.each do |method| 
  self.send(method, "abc")
end 

Comments

2

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

Comments

0

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

send("method_name", "abc", {add more parameters in this hash})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.