zhon zhon - 4 months ago 10
Ruby Question

Accessing ruby method's symbol contained in a module

Given Ruby 2.2

module A
def self.a
"a"
end
end


How do I access
A.a
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 }
x.call


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

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

Answer

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"