Today I Learned

hashrocket A Hashrocket project

Construct A Constant From A String

Ruby's Module.const_get can be used to look for and retrieve the constant for a given name.

This can be used to construct a class name

> Object.const_get("Math")
#=> Math
> Object.const_get("Math")::PI
#=> 3.141592653589793

It can also be used to reference a constant

> Object.const_get("Math::PI")
#=> 3.141592653589793

You can even be more specific if you'd like

> Math.const_get("PI")
#=> 3.141592653589793

Symbols are valid as well

> Math.const_get(:PI)
#=> 3.141592653589793
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.