dsp_099 dsp_099 - 7 months ago 8
Ruby Question

Is it possible to swap out nearly identical classes in Ruby?

class Parent
def punish!
end
end

class Mom < Parent
end

class Dad < Parent
end


If I have an instance of
Dad
but want to make it an instance of
Mom
, is this possible in Ruby?

Answer

If by "swap" you mean substitute in the context of a variable:

parent = Mom.new
parent.punish!

parent = Dad.new
parent.punish!

You can reassign a variable at any time. What you can't do is pervert an instance of object from one class into another. Once created it's basically stuck in that class.

The same principle here applies to object attributes and other places where an object reference might be saved.

Comments