Dynamically access class constants?

I've been looking for a method similar to:

Obj.send(:method)

but to access class constants. So if I have:

class MyObj
  MY_CONSTANT_1
end

I want to access MyObj::MY_CONSTANT_1 by using a variable like foo =
MY_CONSTANT_1 and then MyObj::send(:foo), but obviously send is only
meant to work with methods and not constants.

Is there any way to do this? I've looked but am having difficulty
finding anything.

Thanks,
Marli

···

--
Posted via http://www.ruby-forum.com/.

Marli Ba wrote:

I've been looking for a method similar to:

Obj.send(:method)

but to access class constants. So if I have:

class MyObj
  MY_CONSTANT_1
end

I want to access MyObj::MY_CONSTANT_1 by using a variable like foo =
MY_CONSTANT_1 and then MyObj::send(:foo), but obviously send is only
meant to work with methods and not constants.

Is there any way to do this? I've looked but am having difficulty
finding anything.

Thanks,
Marli
  
I am slightly confused by your example, but you definitely need Module#const_get: class Module - RDoc Documentation

irb(main):001:0> class A
irb(main):002:1> B = 1
irb(main):003:1> end
=> 1
irb(main):004:0> A.const_get(:B)
=> 1

-Justin

class MyObj
  MY_CONSTANT_1 = "hello"
end

=> "hello"

c = "MY_CONSTANT_1"

=> "MY_CONSTANT_1"

MyObj.const_get(c)

=> "hello"

···

--
Posted via http://www.ruby-forum.com/\.

Justin Collins wrote:

I am slightly confused by your example, but you definitely need
Module#const_get:
class Module - RDoc Documentation

irb(main):001:0> class A
irb(main):002:1> B = 1
irb(main):003:1> end
=> 1
irb(main):004:0> A.const_get(:B)
=> 1

-Justin

Ah, sorry for the confusion. const_get is exactly what I was looking
for though, thanks!

···

--
Posted via http://www.ruby-forum.com/\.