From: William James Date: 2007-05-04T11:10:04+09:00 Subject: Re: Is there a better way to do this? On May 3, 8:38 pm, 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 Without 'enumerator': def sform( str, fmt ) ary = str.split(//) fmt.gsub( /0/ ){ ary.shift } end