Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby convert string to method name

Tags:

methods

ruby

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!!

like image 578
verdure Avatar asked Nov 07 '11 12:11

verdure


People also ask

What is TO_A in Ruby?

The to_a() is an inbuilt method in Ruby returns an array containing the numbers in the given range. Syntax: range1.to_a() Parameters: The function accepts no parameter. Return Value: It returns an array containing all the numbers.

How do you turn a string into a method?

To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.

How do you convert a string to a method in Ruby?

Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.

What is TO_S in Ruby?

The to_s function in Ruby returns a string containing the place-value representation of int with radix base (between 2 and 36). If no base is provided in the parameter then it assumes the base to be 10 and returns.


1 Answers

Best way is probably:

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

See Object#send

like image 153
Chowlett Avatar answered Oct 06 '22 00:10

Chowlett