We learned about
eval and its ideas in the last lesson.
instance_eval is a similar method on the
Object class that takes in Ruby code embedded in a string and two other optional arguments.
One of the major differences between
instance_eval is that with
instance_eval you have the choice of explicitly handling the context of
instance_eval is a method on
Object it is scoped by the object you specify.
Although this scoping within an object might seem a bit restrictive, it isn't necessarily more secure, as the devil still lies in its ability to evaluate code within a string.
If you look at the above example again, you'll notice that we've ended up defining a class method on
Monk. Our method is called
instance_eval, so why did it define the method as a class method? Let's go back to what we learned in the Classes lesson from the Ruby Primer.
Class. These classes that have instances as other classes are known as
Therefore, we've ended up creating this method on an object which is an instance of the class
Class that in our case is
Monk. Hence, the name
And as we know, class methods are called as
Monk.method. Class objects are created by calling
Monk.new. So the above is equivalent to doing this:
instance_eval works by treating the object as it were an instance of something. Implying a
self context to the receiving object.
Get your head around this oddity, by solving this exercise.
instance_eval to get access to your class' object data. Instance variables are created when you create a new instance from your class.
You get a hold of
@zen because now you've instantiated a new object that holds the value of
@zen and the context has been set to
instance_eval can also accept a block instead of a string. If you haven't already, it is advisable to read the Blocks lesson on Ruby Primer before solving the rest of this chapter.