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

末鹿安然 提交于 2020-01-11 08:29:25

问题


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?


回答1:


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.




回答2:


When I needed to convert from the built-in String class to a custom class called MyString, I did it via 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:


simple answer, no:

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

however you can delete methods and mix in modules and such so as to leave an object that looks totally different...



来源:https://stackoverflow.com/questions/7528552/is-it-possible-to-change-the-class-of-a-ruby-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!