I defined the class Rectangle:
class Rectangle
attr_reader :b, :h
def initialize(b, h)
@b = b
@h = h
end
def area
@b*@h
end
def to_s
"Rectangle #{@b}x{@h}"
end
end
and its subclass Square:
class Square < Rectangle
attr_reader :s
def initialize(s)
@s = s
super(@s, @s)
end
def to_s
"Square of side #{@s}"
end
end
Now, let's say I defined a Rectangle object r = Rectangle.new(5, 5), but actually it should be a Square because I'd like r.to_s to return "Square of side 5".
I can define a to_square method in the Rectangle class that returns a Square object equivalent to r, but, is it possible to write a to_square! method that would actually change the r class to Square without returning another object, so that r.class would now return Square instead of Rectangle?
And, what if I'd like:
Square(r)
to return the Square equivalent object of r, just like:
Integer("3")
which returns the Integer 3?
Is that possible? And, if so, how?