Is it possible to change the class of a Ruby object?

后端 未结 3 1219
-上瘾入骨i
-上瘾入骨i 2021-01-18 03:41

Is it possible to change the class of a Ruby object once it has been instantiated, something like:

class A
end

class B
end

a = A.new
a.class = B

3条回答
  •  独厮守ぢ
    2021-01-18 03:58

    No, this is not possible from within ruby.

    It is theoretically possible from within a C extension by changing the klass pointer of the given object, but it should be noted that this will be completely implementation-specific, will not work for immediate types (i.e. you definitely can't change the class of e.g. a fixnum), and might blow up in various ways.

提交回复
热议问题