zhon zhon - 1 year ago 45
Ruby Question

Accessing ruby method's symbol contained in a module

Given Ruby 2.2

module A
def self.a

How do I access
so I can assign to a variable and call it later?

I have tried the following:

x = A::a.to_sym
send x # NoMethodError: undefined method `a' for main:Object

The following works:

x = -> { A.a }

Since I have both namespaced functions and non namespaced functions in an array is there a way I can do this with

I really don't want to pollute the namespace with
include A

Answer Source

You can get a callable object (i.e. an object that supports #call just like a proc) using the method method:

a = A.method(:a)
a.call # Or a[] or a.() as you prefer.
# "a"