Q: how to undefined a class after declaration?


#1

E.g. using irb, I created class A and then class B, later I realized
what I wanted was class B to be a subclass of A like ‘class B < A’. irb
would not allow that now that B exists. How do I undefined B so that I
can create a new class B with inheritance to A. Is there an undef for
class ?

Thanks in advance.
Mike C


#2

On Apr 27, 2006, at 12:47 AM, mike chang wrote:


Posted via http://www.ruby-forum.com/.

irb(main):001:0> class A
irb(main):002:1> end
=> nil
irb(main):003:0> class B
irb(main):004:1> end
=> nil
irb(main):005:0> class B < A
irb(main):006:1> end
TypeError: superclass mismatch for class B
from (irb):5
irb(main):007:0> class Object
irb(main):008:1> remove_const ‘B’
irb(main):009:1> end
=> B
irb(main):010:0> class B < A
irb(main):011:1> end
=> nil


#3

Thanks Logan C… It works.
But … can you help me explain why my instance object ‘b’ and its
methods are still reachable after remove_const on class ‘B’?

E.g.
irb(main):001:0> class A
irb(main):002:1> def show
irb(main):003:2> p “i am A”
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> class B
irb(main):007:1> def show
irb(main):008:2> p " i am B"
irb(main):009:2> end
irb(main):010:1> end
=> nil
irb(main):011:0> b = B.new
=> #<B:0x3866ad8>
irb(main):012:0> b.show
" i am B"
=> nil
irb(main):013:0> class Object
irb(main):014:1> remove_const ‘B’
irb(main):015:1> end
=> B
irb(main):016:0> class B < A
irb(main):017:1> def show
irb(main):018:2> p “i am B, child of A”
irb(main):019:2> end
irb(main):020:1> end
=> nil
irb(main):021:0> b2 = B.new
=> #<B:0x38456e8>
irb(main):022:0> b2.show
“i am B, child of A”
=> nil
irb(main):023:0> b.show
" i am B"
=> nil
irb(main):024:0>

Thanks again.


#4

On Apr 27, 2006, at 1:24 AM, mike chang wrote:

=> nil
=> nil
irb(main):021:0> b2 = B.new


Posted via http://www.ruby-forum.com/.

remove_const just removes the constant named ‘B’. Your instances
still have a pointer to the same object that the constant B pointed to.

Pretend if you will that constants are in a hash.

constants = { “B” => # }

class B # look up constants[‘B’], if it doesn’t exist, then do
constants[‘B’] = Class.new. Regardless add the following methods to it.
end

b = B.new # Construct an object that kinda looks like #<some object
@class=# >

class Object; remove_const ‘B’; end # does something akin to
constants.delete(‘B’)

Now b still has an instance variable (of sorts) that points to the
actual class information. A constant like any variable in ruby is
just a label, remove_const removes the label, not the actual object.