1

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
joanx737
  • 337
  • 1
  • 3
  • 19

3 Answers3

2

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:

Community
  • 1
  • 1
Lucas Wilson-Richter
  • 2,274
  • 1
  • 18
  • 24
1

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]
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
-2
DailyQueries.send(queries[i])

....................

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 4
    While technically correct, your answer does not explain why your solution works. Think about how you can make your answer more useful instead of padding it with garbage. – Justin Howard Feb 05 '16 at 04:15
  • 2
    @JustinHoward Legend has that sawa does not spend more than few microseconds to answer questions using his [HHK](http://www.amazon.com/Happy-Hacking-Keyboard-Professional2-Black/dp/B000EXZ0VC) :D – Wand Maker Feb 05 '16 at 06:52