Reputation: 1630
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
Upvotes: 2
Views: 749
Reputation: 434585
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"
Upvotes: 5
Reputation: 110665
Yes, you can use send
:
A.send :a #=> "a"
or
A.send "a" #=> "a"
Upvotes: 2
Reputation: 4563
A::a
is a method, so you can simple do:
m = A.method :a
m.call # returns "a"
Upvotes: 2