x.instance_eval changes your context, so self evaluates to x .
This allows you to do many things, including defining instance variables and instance methods, but only for x.
x = Object.new y = Object.new # define instance variables for x and y x.instance_eval { @var = 1 } y.instance_eval { @var = 2 } # define an instance method for all Objects class Object def var @var end end x.var #=> 1 y.var #=> 2
Ruby allows you to define instance methods for an object in several places. As usual, one defines them in the class, and these instance methods are distributed among all instances of this class (for example, def var above).
However, we can also define an instance method for only one object:
# here one way to do it def x.foo "foo!" end
Even if x and y have the same class, they do not share these methods, since they were defined only for x .
x.foo #=> "foo!" x.bar #=> "bar!" y.foo #=> raises NoMethodError y.bar #=> raises NoMethodError
Now in ruby ββall objects, even classes. Class methods are only instance methods for this class object.
Remember once again that all these methods are A specific, B does not gain access to any of them:
A.baz #=> "baz!" B.telegram #=> raises NoMethodError
Itβs important to distract from here that class is just the instance methods of an object of class Class
rampion May 23 '09 at 3:00 a.m. 2009-05-23 03:00
source share