Reputation: 367
I'd like to know how to call a method with a varying name. I have:
queries = ['new_teachers']
I'd like to call the method new_teachers
on a module DailyQueries
using a reference to the array element like DailyQueries[queries[i]]
, which should be equivalent to DailyQueries.new_teachers
. Any help greatly appreciated.
Upvotes: 1
Views: 117
Reputation: 2324
You can use the public_send
method to call an arbitrary method on an object. For example, foo.public_send(:bar)
is equivalent to foo.bar
, and works exactly the same way.
Knowing this you can define an array of symbols, where each symbol is a method you want to call. So:
[:bar, :baz, :qorg].each {|method|
DailyQueries.public_send(method)
end
will work the same as:
DailyQueries.bar
DailyQueries.baz
DailyQueries.qorg
Here's some reading material if you'd like to learn more about the public_send
method, and its less privacy-respecting cousin, the send
method:
Upvotes: 2
Reputation: 18762
If you need just a way to call a method if a variable has method name string, then, refer to @sawa's answer. If, for some specific reason, you need to invoke a module method using []
syntax, then, read on.
If you say method is part of module, then, it must be its singleton method as shown below, only then, you can invoke it using DailyQueries.new_teachers
syntax
module DailyQueries
def self.new_teachers
["A", "B"]
end
end
You cannot invoke module methods using []
syntax - hence, you may have to add a method to module that does this for you.
module DailyQueries
def self.[] name, *params
method(name)[*params]
end
#... other methods definitions
end
Now, you can do this:
DailyQueries[queries[0]]
If the method had any parameters, you can pass arguments as:
DailyQueries[queries[0], "param1", "param2", :another_param]
Upvotes: 1