Can I change the class of a Ruby object?

Is it possible to change the class of a Ruby object after it is created, for example:

class A end class B end a = A.new a.class = B 

or similar.

(the above code does not execute because the class is a read-only variable)

I know that this is impractical, a bit strange, and not what I plan to do, but is this possible?

+7
source share
3 answers

No, this is not possible from within ruby.

It is theoretically possible from within the C extension by changing the klass pointer of this object, but it should be noted that this will be completely implementation-specific, will not work for immediate types (i.e. you can’t change the class, for example, fixnum) and may explode different ways.

+6
source

When I needed to convert from a built-in String class to a custom class called MyString , I did this through the following:

 class MyString < String #Class body here end class String def to_MyS MyString.new self end end foo = "bar" puts foo.class #=> String foo = foo.to_MyS puts foo.class #=> MyString 
+3
source

simple answer no:

 NoMethodError: undefined method `class=' for #<A:0x91a758> 

however, you can delete methods and mix them in modules and in such a way as to leave an object that looks completely different ...

+1
source

All Articles