From: "Michael W. Ryder" <_mwryder@...> Date: 2007-05-04T11:05:06+09:00 Subject: Re: Is there a better way to do this? Dan Zwell wrote: >> 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. >> >> > > welcome. > > > require 'enumerator' > > def sform(num, fmt) > # convert num to array (of one digit strings): > num = num.to_enum(:each_byte).map { |code| code.chr } > > # for each zero, replace it with a digit popped off the > # front of the array of numbers (or characters): > fmt.gsub(/0/) { num.shift } > end > > > dan > Your method is much better than my C style one. With a little work to handle exceptions it should generally work. The only problem I have found so far is that it doesn't handle periods in the number string properly -- i.e. sform("12345.67", "$00,000.00") returns $12,345..6" instead of $12,345.67". Something for me to work on. Thanks for the code.