Giorgio Robino Giorgio Robino - 1 year ago 84
Ruby Question

How to call a method with dynamic dispatch (when method is part of a Module), in Ruby?

In Ruby language, I have to call dynamically a method that belong to a Module, having method name as a stored string (say:


Let's consider this case:

module Dialogs
def paperino(param)
puts "paperino. param: #{param}"

How can I do .call( "parametro") in run-time ?

I explain better:

In case the method is part of a class I know how to do:
I Instantiate the class (from the string and I call the method object):

class Dialogo
def pluto(param)
puts "pluto. param: #{param}"

class_name = "Dialogo"
# create class symbol from a string
class_symbol = Kernel.const_get(class_name)

# return a new instance
class_instance =

# Instantiating a method object
method_object = class_instance.method(:pluto)

# call the method in run time: "parametro_pluto"

And the simpler situation of a method without an explicit class

def pippo(param)
puts "pippo. param: #{param}"

method_object = Kernel.method(:pippo) "parametro"

But what is the syntax to call dynamically a method that is part of a Module?

In the following example:

module Dialogs
def paperino(param)
puts "paperino. param: #{param}"

the method I wish to call is "Dialogs::paperino"

BTW, I don't want to use neither send() or eval(), but just a call().


Answer Source

I don't think you can. Methods defined in that way on a Module are not meant to be accessed directly.

NoMethodError: undefined method `paperino' for Dialogs:Module

You could define it on Dialogs using self

def self.paperino(param)

And then you will be able to access it with method


If you need to define it as def paperino(param) here is a way you could access the method.

method = ('foo')

This defines a new object and then extends that object with the module Dialogs. Then you can get the method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download