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

后端 未结 3 1132
-上瘾入骨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:46

    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
    

提交回复
热议问题