I have some code that calculates the nth root of a number. Right now, that method only works on Fixnum, because I defined it inside the Fixnum class. It would be very easy to just do
class Float
#same code as was in Fixnum
end
but that seems unneccessary. I have no idea how to dynamically call classes. I tried:
classes = [Fixnum, Float]
classes.each do |x|
x.instance_eval do
def root(pow)
return self ** (1/pow.to_f)
end
end
end
but that did not work. How do I do this?
Note: After posting, I realized this might be a better fit for Programmers.SE, as it is theoretical, as well as single-problem based. Feel free to migrate accordingly…
The relevant part of the class hierarchy looks like this:
NumericIntegerFixnumandBignumas subclasses ofInteger.FloatRationalSo patch your change into Numeric to cover them all at once:
Then you can do these things: