From: Harry Kakueki Date: 2007-05-04T17:24:02+09:00 Subject: Re: Is there a better way to do this? On 5/4/07, Robert Klemme wrote: > > Is there a better (more Rubyish) way to do this? > > Obviously I will want to add more code in the future to handle > > exceptions like phone numbers that are not 10 characters long or are > > longer, but this will get me started. > > I'd start by having the parts of the number separate. Then you can > easily use sprintf for the formatting. For example, with > > Phone = Struct.new(:country, :area, :number) do > def to_s > sprintf("(%d) %d-%d", country, area, number) > end > end > > You can do > > irb(main):006:0> a = Phone.new 123, 456, 7890 > => # > irb(main):007:0> puts a > (123) 456-7890 > => nil > irb(main):008:0> > > You can even add exceptions and special handling if one of the parts is > missing etc. If you need leading zeros, that's easy with sprintf as well. > > Kind regards > > robert > > I answered that question, too. But then he added more requirements. He not only wants to deal with phone number formats, but any format. Harry -- http://www.kakueki.com/ruby/list.html A Look into Japanese Ruby List in English