Calling a Method from a String With the Method'S Name in Ruby

Calling a Method From a String With the Method's Name in Ruby

To call functions directly on an object

a = [2, 2, 3]
a.send("length")
# or
a.public_send("length")

which returns 3 as expected

or for a module function

FileUtils.send('pwd')
# or
FileUtils.public_send(:pwd)

and a locally defined method

def load()
puts "load() function was executed."
end

send('load')
# or
public_send('load')

Documentation:

  • Object#public_send
  • Object#send

Get method name as string or symbol in ruby

After this the line m = [ method1, method2 ] the variable m has no information anymore about the methods that were called to assign [1, 2] to m.

Therefore, instead of storing the values that were returned by the methods I purpose to just store the method names in the array and use public_send to call the method when you need both their names and their return values:

m = [:method1, :method2]

def method1
1
end

def method2
2
end

m.each { |name| puts "#{name}: #{public_send(name)}" }
# => method1: 1
# method2: 2

Or you might want to use a hash to store the method names and the returned values right away when assigning tehm to m:

m = { method1: method1, method2: method2 }
m.each { |name, value| puts "#{name}, #{value}" }

How to call methods dynamically based on their name?

What you want to do is called dynamic dispatch. It’s very easy in Ruby, just use public_send:

method_name = 'foobar'
obj.public_send(method_name) if obj.respond_to? method_name

If the method is private/protected, use send instead, but prefer public_send.

This is a potential security risk if the value of method_name comes from the user. To prevent vulnerabilities, you should validate which methods can be actually called. For example:

if obj.respond_to?(method_name) && %w[foo bar].include?(method_name)
obj.send(method_name)
end

String to method name

method(action).call

or

public_send(action)

Example:

method(action).call
#=> James
public_send(action)
#=> James

Be aware, though, that none of the above cares about the context, where was method originally defined, so both will call it in the context of the current object.

Ruby convert string to method name

Best way is probably:

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

See Object#send

How to turn a string into a method call?

Object#send

>> a = "class"
>> "foo".send(a)
=> String

>> a = "reverse"
>> "foo".send(a)
=> "oof"

>> a = "something"
>> "foo".send(a)
NoMethodError: undefined method `something' for "foo":String

Pass a method name as string to other method of different class in Ruby?

I think you need to transform your string in a symbol

"foo".to_sym

And your code:

class Core
def main_test (validation_obj, validation_method)
par1 = 'sample'
validation_obj.send validation_method.to_sym, par1
# other way #
# validation_method.call(par1)
end
end

I believe this will make work your code.

Call a method on a variable where the method name is in another variable

Use send to send a message to an object:

@car.send(label.related_to)

If there is any chance of label.related_to not being a valid method for the object, you'll probably want to be prepared to catch the NoMethodError

Calling a method using the string/variable of the method name inRuby

Check out send

send(@command) if respond_to?(@command)

The respond_to? ensures that self responds to this method before attempting to execute it

For the updated get_usage() part I would use something similar to this:

def execute
case @command
when '--help', '-h', 'help'
get_usage()
# more possibilities
else
if respond_to?(@command)
send(@command)
else
puts "Unknown command ..."
end
end
end


Related Topics



Leave a reply



Submit