Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

object

class

ruby

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?

like image 989
superluminary Avatar asked Sep 23 '11 11:09

superluminary


People also ask

Are Ruby classes objects?

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.

What is new () in Ruby?

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 does .class do in Ruby?

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.

Does Ruby have class methods?

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.


1 Answers

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.

like image 71
sepp2k Avatar answered Oct 02 '22 18:10

sepp2k