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?
Ruby is a pure object-oriented language, which means that in the Ruby language, everything is an object. These objects, regardless of whether they are strings, numbers, classes, modules, etc., operate in a system called The Object Model.
Creating Objects in Ruby using new Method You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.
What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects.
There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With