From: James Edward Gray II Date: 2005-03-23T06:26:12+09:00 Subject: Re: Any guides for good coding in Ruby? On Mar 22, 2005, at 3:09 PM, Arfin wrote: > Is there some kind of class to format numbers? Something to let you > transform: > > 1 => "0001" > 1234 => "1,234.00" I'm not aware of a core Ruby tool for commiying numbers, but it's not hard to roll a solution: def commify( number ) � � � � text = number.to_s.reverse � � � � text.gsub!(/(\d\d\d)(?=\d)(?!\ d*\.)/, '\1,') � � � � text.reverse end > I needed to display the day and month in a 00 format and the way I did > it was adding a method to the Integer class > > class Integer > def addZero > return "0" + self.to_s if self.to_s.length == 1 > return self.to_s > end > end > t = Time.now > p "The date is: #{t.year}#{t.month.addZero}#{t.day.addZero}" > > What do you guys think of this solution? Kernel#sprintf and it's shortcut cousin String#% will handle this for you. Here's an example: "%02d" % 1 => "01" Also look into Time#strftime for tasks like the above. > On a side note, could you guys give a few rules of thumb you follow in > order to make your code clean and readable? Of course, there are loads of rules here and every person that gives you a list will be different. Common sense ideas like, "Use good variable names," apply in Ruby as they do everywhere else. One of Ruby's great strengths is readability, I think. Play to your strengths. Give the extra five keystrokes to make things utterly clear, but don't be verbose if a concise line of code is obvious. As always, common sense is needed. James Edward Gray II