是否可以更改Ruby对象的类? [英] Is it possible to change the class of a Ruby object?

查看:277
本文介绍了是否可以更改Ruby对象的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦实例化,可以更改Ruby对象的类,例如:

  class A 
end

class B
end

a = A.new
a.class = B



或类似。



(上述代码不会作为类运行,变量)



我知道这是不可取的,有点奇怪,而不是我打算做的,但是可能吗?



这在理论上是可能的,从一个C扩展通过改变给定对象的 klass 指针,但是应该注意,这将是完全实现特定的,不会为立即类型工作(即你肯定不能改变例如fixnum的类),并且可能以各种方式爆炸。


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

or similar.

(the above code does not run as class is a read only variable)

I know this is not advisable, a bit strange, and not something I plan on doing, but is it possible?

解决方案

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.

这篇关于是否可以更改Ruby对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆