From: Chris Shea Date: 2008-05-16T14:25:02+09:00 Subject: Re: A Couple of Questions Regarding Ruby Style On May 15, 10:52 pm, "Michael W. Ryder" <_mwry...@worldnet.att.net> wrote: > While working on my rational class I came up with a couple of questions > regarding the accepted way to do things. I looked up a couple of Style > guides on the net but they seemed to cover only the formatting of code > and not what I was looking for. > The first is when casting is it preferred to use Integer(x) or x.to_i? > Being from a C background the first is more obvious to me as it states > that I am converting x to an Integer. The second has its place when > chaining several changes to a variable but I can't see it as being clearer. It depends, mostly, on how loose you want to be. For example, when dealing with strings, Integer only takes strings that represent an integer value. So Integer('10'), Integer('0xA'), and Integer('012') all work fine (and happen to represent the same value). However, strings that don't JUST represent an integer raise an ArgumentError. Integer('10.0') and Integer('10 eggs') fail. String#to_i is much freer with what you can do. '10 eggs'.to_i gives you 10, as does '10.1'.to_i. (Though, be aware that '10'.to_i != '0xA'.to_i) Choosing between the two is simply a matter of deciding which behavior is more desirable. > The second involves the initialization method for a class. I am making > it so that the .new method will accept Integers, Floats, Strings, and > Rational numbers. Should I be doing this, or should I require that all > the converting be done before calling new? If I allow any type of > Numeric, or String representation, is it acceptable to have the method > call other methods for some of the conversions? If it will make the life of someone using this library easier to pass in Integers, Floats, Strings, or Rationals (and I suspect that it will), I bet allowing it will be worth the effort. And it is perfectly acceptable for the initialize method call other methods for conversion or whatever you need when a new instance is created. HTH, Chris