1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00
Files
til/ruby/construct-a-constant-from-a-string.md
2015-09-23 20:55:04 -05:00

641 B

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