On Feb 22, 2006, at 4:03 PM, Anthony DeRobertis wrote:

> Take the following snippet:
>
> module SomeModule
>   class SomeClass
>     SomeConstant = 3.1415
>   end
> end
>
>    var = "SomeModule::SomeClass"
>    print(var::SomeConstant)
>
> This raises TypeError. So far, the only way I've found to do this (and
> let me warn you, I'm quite new to Ruby so I may just be missing
> something right in front of me) is like this:
>
>   var = "SomeModule::SomeClass"
>   eval "var = " + var
>   print(var::SomeConstant)
>
> which does indeed work, but I figure there has got to be a better way
> than using eval.

The usual idiom for this is const_get().  It's a little tricky in  
this case, because of the nesting though:

 >> module SomeModule
 >>   class SomeClass
 >>     SomeConstant = 3.1415
 >>   end
 >> end
=> 3.1415
 >> var = "SomeModule::SomeClass"
=> "SomeModule::SomeClass"
 >> consts = var.split("::")
=> ["SomeModule", "SomeClass"]
 >> cls = consts.inject(Object) { |last, cur| last.const_get(cur) }
=> SomeModule::SomeClass
 >> puts cls::SomeConstant
3.1415
=> nil

Hope this gives you some fresh ideas.

James Edward Gray II