Forum: Ruby "restoring" classes after changing stuff

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
5ef2a067cc3a4f49021b6f781cabf7bb?d=identicon&s=25 Marcelo Alvim (Guest)
on 2007-04-16 23:35
(Received via mailing list)

Well, I'm new to Ruby (I've been working and playing with it for the
last 6 months only), and
I know there's probably another way in which this could work, but
somehow I feel like the
code below should work. Let's see what you guys think about it.

The idea is making a copy of a class object, changing it and then
restoring it back to what it was after playing with the new stuff I
added. It should go somewhat like this:

OldArray = Array.dup
# => OldArray

class Array
    def my_method; "My Method"; end
# => nil

# => "My Method"

x =
# => []

# => "My Method"

### Switch back
Array = OldArray.dup
(irb):9: warning: already initialized constant Array
# => Array

# => "My Method"

(Ok, now why did that work? Maybe "x" is still using the modified Array

# => "My Method"

(Same thing here, it seems)

[1, 2, 3].my_method
# => "My Method"

(Hmmmm, let's try something different)

x =
# => []

NoMethodError: undefined method `my_method' for []:Array
        from (irb):14
        from :0

(Ok, so new instances only? Is this weird at all, or is this the way
it's supposed to work?)

I'm asking these questions out of real lack of knowledge, and I REALLY
don't suppose
something should change in order to make this work. I'm just trying to
understand how
Ruby does all this stuff.

Thank you in advance,
Marcelo Alvim.
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2007-04-17 00:23
(Received via mailing list)
On Tue, 17 Apr 2007, Marcelo Alvim wrote:

> added. It should go somewhat like this:

you can't easily undo class changes.  better to not make them in the
place.  this will work

harp:~ > cat a.rb
module ProxyClass
   def parent do
       const_set :PARENT, parent
       instance_methods.each{|m| undef_method m unless m[%r/__/]}
       c = self and define_method(:class){ c }
       def method_missing m, *a, &b
         self.class::PARENT.instance_method(m).bind(self).call(*a, &b)
class Class
   def proxy() end

A = Array.proxy

class A
   def foo() :foo end

a = A[ 0, 1, 2 ]

p a.class
p a[0]
p a.first(2)

harp:~ > ruby a.rb
[0, 1]


This topic is locked and can not be replied to.