From: Josef 'Jupp' Schugt Date: 2005-03-24T07:17:02+09:00 Subject: Re: Any guides for good coding in Ruby? Arfin wrote: > 1234 => "1,234.00" I only handle the non-obvious "1234.00" -> "1,234.00" part of the task but that one for float and integer regardless of length and sign. The only minor trick is using positive lookahead to extract the right digits in the case of a string that represents a float. Note that the argument is left unchanged if - it is no string - it neither matches /^[-+]?\d+\.\d+$/ nor /^[-+]?\d+$/ The latter means that no modification is done if exponential notation is used. This is done on purpose because one would not expect colons in such a notation. Extending the algorithm to numbers with leading zeroes is left as an exercise to the reader :-> Here is the HOW IT IS DONE: def threepack(x) return x unless x.class == String if /^[-+]?\d+\.\d+$/.match(x) match = /((\d\d\d)+)(?=\.)/.match(x) elsif /^[-+]?\d+$/.match(x) match = /((\d\d\d)+)$/.match(x) end return x if match.nil? result = match.pre_match temp = match[1] until temp.empty? result << ',' unless ['', '-', '+'].member?(result) result << temp[0..2] temp = temp[3..-1] end result << match.post_match unless match.post_match.nil? result end testdata = [ 12345678, '08/15', '4711 Eau de Cologne', 'Beethoven', '%d' % 1, '%d' % 12, '%d' % 123, '%d' % 1_234, '%d' % 12_345, '%d' % 123_456, '%d' % 1_234_567, '%d' % -1, '%d' % -12, '%d' % -123, '%d' % -1_234, '%d' % -12_345, '%d' % -123_456, '%d' % -1_234_567, '%4.2f' % 1.0, '%5.2f' % 12.0, '%6.2f' % 123.0, '%7.2f' % 1_234.0, '%8.2f' % 12_345.0, '%9.2f' % 123_456.0, '%10.2f' % 1_234_567.0, '%5.2f' % -1.0, '%6.2f' % -12.0, '%7.2f' % -123.0, '%8.2f' % -1_234.0, '%9.2f' % -12_345.0, '%10.2f' % -123_456.0, '%11.2f' % -1_234_567.0, ] testdata.each{|x| puts threepack(x)} Here is the WHAT IS DONE: 12345678 08/15 4711 Eau de Cologne Beethoven 1 12 123 1,234 12,345 123,456 1,234,567 -1 -12 -123 -1,234 -12,345 -123,456 -1,234,567 1.00 12.00 123.00 1,234.00 12,345.00 123,456.00 1,234,567.00 -1.00 -12.00 -123.00 -1,234.00 -12,345.00 -123,456.00 -1,234,567.00 Before someone asks: The examples were not chosen by chance; I live in the former FRG capital of Bonn where Beethoven was born that is located near Cologne. Josef 'Jupp' Schugt -- This space is intentionally left void.