From: "Michael W. Ryder" <_mwryder@...> Date: 2007-05-04T10:25:04+09:00 Subject: Re: Is there a better way to do this? Harry Kakueki wrote: > On 5/4/07, Michael W. Ryder <_mwryder@worldnet.att.net> wrote: >> As part of my learning Ruby I am trying to learn how to format strings. >> The following is an example for formatting a U.S. phone number: >> >> a = "1234567890" >> b = "(000) 000-0000" >> ai = 0 >> >> for i in 0..(b.length) -1 >> if b[i,1] == "0" >> b[i,1] = a[ai,1] >> ai += 1 >> end >> end >> puts b >> >> 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'm sure there are better ways but here is something to look at. > > a = "1234567890" > area = a.slice(0..2) > exc = a.slice(3..5) > num = a.slice(6..9) > tel = "(#{area}) #{exc}-#{num}" > > p tel > > Harry > > I am trying to come up with a "generic" formatting routine so that I could feed it something like sform("123456789", "000-00-0000") or sform("1234567890", "(000) 000-0000") or sform("123456", "00/00/00") and it would work. I could easily do something like you suggest, and for some cases it might be better, but I want something I can for any number of formats. Thanks for the input.