Joel VanderWerf wrote: > Michael W. Ryder wrote: >> I am part way through implementing a Rational math class to further my >> understanding of Ruby and had a couple of questions that I can't find >> the answer to in Pickaxe. >> The first question regards creating a new instance of the class. The >> initialize method expects two integer values. While I have no problem >> making sure that they are integers I am not sure what to do if they are >> not. Do I return nil or some other result? > > You could raise an exception: > > unless ... > raise ArgumentError, "Rational arguments must be integers" > end > That worked except for a minor problem. I first tried a.class == Integer and it failed. I had to use Fixnum to get it to work. I thought that Integer being the super class for Fixnum and Bignum I could just test for Integer without having to test for both of the subclasses. Is there any way to do this? >> The other question is how to override basic math operations like >> addition and multiplication. I could implement them as x.add(y) but >> would prefer to just be able to enter x + y. I think I have to create a > > class Myclass > def +(x) > ... > end > end > I didn't think it would be that easy, but I guess it was. >> new instance of the class for the result and return that but am not sure >> how to make it so that Ruby calls the right method when it sees x + y. >> On a related note is there any good source for writing operations like >> the math and probably coerce? If I can get the math working the >> comparable operations should be "trivial". > > There's some explanation of how to write coerce methods in the PickAxe > (p. 358 of my 2nd ed. pdf copy). > I found the example in my copy at the same place. I just didn't notice it when scanning the book earlier trying to find the information. Thanks for the assistance.