From: Brian Candler Date: 2007-05-04T16:42:31+09:00 Subject: Re: Is there a better way to do this? On Fri, May 04, 2007 at 09:45:04AM +0900, 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? I have a vague recollection that Perl has a specific feature along these lines: ah yes, see "man perlform". But I've never used it, and I think this is one Perlism that Ruby hasn't copied. It sounds to me like you actually want two different types of format: format("000 000-0000","1234567890") # => "123 456-7890" format("000000.00","1234.4") # => " 1234.40" People have given you several solutions for the former. The latter is most easily handled by sprintf (or format % [values]) if the value is numeric. Actually, you could bend sprintf to do the former too: val = "1234567890" fmt = "(000) 000-0000" res = sprintf(fmt.gsub(/0/,"%s"), *val.split(//)) Regards, Brian.