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
Rails Activerecord Perform Group, Sum and Count in One Query
Difference Between "Or" and || in Ruby
Why Does Ruby 1.9.2 Remove "." from Load_Path, and What's the Alternative
How to Download a Binary File Over Http
Why How to Refer to a Variable Outside of an If/Unless/Case Statement That Never Ran
In Ruby on Rails, to Extend the String Class, Where Should the Code Be Put In
Continuously Read from Stdout of External Process in Ruby
How to Implement an Abstract Class in Ruby
Understanding [Classone, Classtwo].Each(&:My_Method)
Ruby - Print the Variable Name and Then Its Value
How to Parse a Yaml File in Ruby
How to Test For (Activerecord) Object Equality
How to Convert a Bigdecimal to a 2-Decimal-Place String
Ssl Error When Installing Rubygems, Unable to Pull Data from 'Https://Rubygems.Org/