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.

> 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:

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.

And for completeness reasons you should also implement #eql?, #== and #hash.

Kind regards

	robert