Robert Klemme wrote: > On 20.04.2008 23:43, 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? > > The return value of #initialize is ignored - always. The proper way to > handle this would be to raise an exception - presumably ArgumentError. > My background in older languages is slowing me down. I thought that there might be a way to return a value signifying an invalid entry without having to worry about exception handling. Haven't got that far in Ruby yet. >> 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 new instance of the class for the result and return that but am not >> sure > > Exactly. > >> how to make it so that Ruby calls the right method when it sees x + y. > > You need to implement #coerce, #+, #-, #/, #*, #+@, #-@ - that is if you > want to have full support of basic math. #coerce is a bit tricky but I > am sure there are tutorials around - I just don't have a URL handy. But > you can watch how it works: > I have noticed people using things like #+ before. Is that the same as just + when defining a method? I created a multiplication method using 'def *(x)' and it seems to work fine. Hopefully I can use the coerce method in the Roman numerals class in Pickaxe to create my coerce method. > irb(main):003:0> 1.coerce 2 > => [2, 1] > irb(main):004:0> 1.coerce 2.0 > => [2.0, 1.0] > irb(main):005:0> 1.0.coerce 2 > => [2.0, 1.0] > irb(main):006:0> 1.0.coerce 2.0 > => [2.0, 1.0] > >> 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". > > For comparisons you just need to implement #<=> and then include > Comparable in your class. > This should just be subtracting the two numbers and comparing the results so that should be easy. And not having to define the other methods makes it easier. > And for completeness reasons you should also implement #eql?, #== and > #hash. > Shouldn't #== be inherited from Object? #eql? should be just a matter of comparing the two numbers after "reducing" the fractions. I am not sure on the #hash method though. Do you have any ideas where to start? Thank you for your assistance with this. I am learning a lot from this exercise. > Kind regards > > robert