zhon
zhon

Reputation: 1630

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

Upvotes: 2

Views: 749

Answers (3)

mu is too short
mu is too short

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

Cary Swoveland
Cary Swoveland

Reputation: 110665

Yes, you can use send:

A.send :a  #=> "a" 

or

A.send "a" #=> "a" 

Upvotes: 2

songyy
songyy

Reputation: 4563

A::a is a method, so you can simple do:

m = A.method :a
m.call # returns "a"

Upvotes: 2

Related Questions