Have you ever craved the ability to traverse
all the living objects
in your program? We have! Ruby lets you perform
this trick with
ObjectSpace::each_object
. We can use it to
do all sorts of neat tricks.
For example, to iterate over all objects of type
Numeric
, you'd
write the following.
a = 102.7
b = 95.1
ObjectSpace.each_object(Numeric) {|x| p x }
|
produces:
95.1
102.7
2.718281828
3.141592654
|
Hey, where did those last two numbers come from? We didn't define
them in our program. If you look on page 429, you'll
see that the
Math
module defines constants for e and PI; since we are
examining
all living objects in the system, these turn up as
well.
However, there is a catch. Let's try the same example with different
numbers.
a = 102
b = 95
ObjectSpace.each_object(Numeric) {|x| p x }
|
produces:
Neither of the
Fixnum
objects we created showed up. That's because
ObjectSpace
doesn't know about objects with immediate values:
Fixnum
,
true
,
false
, and
nil
.