Los Módulos ObjectSpace y GC

El módulo ObjectSpace contiene métodos que permiten atravesar los objetos existentes::

>> ObjectSpace.each_object(Numeric) { |x| p x }
2.71828182845905
3.14159265358979
9223372036854775807
95166617196965824296817888526506730120332022876053991446234245250621584887778
2.22044604925031e-16
1.79769313486232e+308
2.2250738585072e-308
0
0
95.1
102.5
=> 11

>> Float::MAX
=> 1.79769313486232e+308
>> Float::EPSILON
=> 2.22044604925031e-16
>> Math::PI
=> 3.14159265358979
>> Math::E
=> 2.71828182845905
El módulo ObjectSpace no accede a los objetos con valores inmediatos: Fixnum, Symbol, true, false y nil:

>> a = 102
=> 102
>> a.class
=> Fixnum
>> b = 95
=> 95
>> ObjectSpace.each_object(Numeric) { |x| p x }
2.71828182845905
3.14159265358979
9223372036854775807
97997521621253453151246418904344427109054468668812181388822276467821973581887
2.22044604925031e-16
1.79769313486232e+308
2.2250738585072e-308
0
0
=> 9
>>
Obsérvese que ObjectSpace.each_object(Class) nos pasa el objeto, no el nombre del objeto:
>> ObjectSpace.each_object(Numeric) { |x| p x.class }
Float
Float
Bignum
Bignum
Float
Float
Float
Bignum
Bignum
=> 9
>>

Podemos inspeccionar los nombres de los métodos de un objeto usando methods:

>> r = 1..10
=> 1..10
>> x = r.methods
=> ["find", "inspect", ..., "include?", "is_a?", "all?"]
>> x.length
=> 94

>> x.index("first")
=> 53
>> w = x[53]
=> "first"

>> m = r.method w
=> #<Method: Range#first>
>> m.arity
=> 0
>> r.send(w)
=> 1

>> m.call
=> 1
>> m.call()
=> 1
>> m[]
=> 1
>>

Casiano Rodriguez León 2015-01-07