From: "Michael W. Ryder" <_mwryder@...> Date: 2007-05-05T03:50:11+09:00 Subject: Re: Is there a better way to do this? Ken Bloom wrote: > On Fri, 04 May 2007 00:43:34 +0000, Michael W. Ryder 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. > > puts a.sub(/(...)(...)(....)/,'(\1) \2-\3') > > when you have other formats, use if a.length == whatever to decide which > pattern to apply. > > --Ken > That looks very interesting! Thanks for the code. I think it will work great for parts of the method. With very little work this I can make this work for formatting dollar amounts, etc.