diff --git a/README.md b/README.md index 12cc7e9..9277fad 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ smart people at [Hashrocket](http://hashrocket.com/). - [Are They All True?](ruby/are-they-all-true.md) - [Assoc For Hashes](ruby/assoc-for-hashes.md) - [Comparing Class Hierarchy Relationships](ruby/comparing-class-hierarchy-relationships.md) +- [Construct A Constant From A String](ruby/construct-a-constant-from-a-string.md) - [Create an Array of Stringed Numbers](ruby/create-an-array-of-stringed-numbers.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) - [Disassemble Some Codes](ruby/disassemble-some-codes.md) diff --git a/ruby/construct-a-constant-from-a-string.md b/ruby/construct-a-constant-from-a-string.md new file mode 100644 index 0000000..eb4a381 --- /dev/null +++ b/ruby/construct-a-constant-from-a-string.md @@ -0,0 +1,28 @@ +# Construct A Constant From A String + +Ruby's +[`Module.const_get`](http://ruby-doc.org/core-2.1.0/Module.html#method-i-const_get) +can be used to look for and retrieve the constant for the given name. + +This can be used to construct a class name + +```ruby +> Object.const_get("Math") +#=> Math +> Object.const_get("Math")::PI +#=> 3.141592653589793 +``` + +It can also be used to reference a constant + +```ruby +> Object.const_get("Math::PI") +#=> 3.141592653589793 +``` + +You can even be more specific if you'd like + +```ruby +> Math.const_get("PI") +#=> 3.141592653589793 +```