2.2 Tap In Deeper

Get constants

We looked at ways of inspecting methods by opening up their object forms and peeking into classes. const_get allows us another form of inspection, not entirely unlike eval; using constant names as a String or a Symbol.
Example Code:

Output Window

It is often used to instantiate classes at runtime, like creating an object of a class for a particular user input. If you're familiar with Rails, then you might have seen this used for instantiating controllers depending on a certain URL being requested. As class names are constants too, it is really easy to do that.
Example Code:

Output Window

Because this is just working with strings that are assumed to be constant names, it would not work if your classes aren't named constants.
Example Code:

Output Window

const_get is defined on Module, but it works for classes as well, as Class is a subclass of Module. It returns a NameError if the value of that constant isn't found. This is the only way you can access nested constants, as const_get only parses properly formed named constants and does not parse colons like Monk::ZEN.
Example Code:

Output Window

This also restricts the scope for the constant search to the class Monk. If it doesn't find the constant in that scope it goes up the ancestral chain and starts looking from Object.
Example Code:

Output Window

eval isn't exactly safe. Modify the Editor exercise from the last lesson to use const_get instead of eval to parse the name of the class in the second filter.

Output Window

Get instance variables

instance_variable_get is a method defined on Object that works much the same way as const_get. It allows you to retrieve the value of an instance variable defined on your class or module.
Example Code:

Output Window

@ is not optional.

Write a method inspect_instance_variable that accepts the name of a class as a String and the name of the instance variable defined on that class (again, as a String) whose value it should return.

Output Window

Using instance_variable_get for metaprogramming and inspection purposes is fine. It is, however, not a particularly good way to normally read the instance variables, as it breaks encapsulation. The preferred way is to define an attr_reader.

Example Code:

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Srushti