From: Josef 'Jupp' Schugt Date: 2005-03-26T06:27:14+09:00 Subject: Re: Any guides for good coding in Ruby? Florian Gross wrote: > Nifty code, though I wonder if it could be simplified by using > String#rindex? I do not see any use of String#rindex that would simplify the code but String#scan can do something for us: 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 result << ',' unless ['', '-', '+'].member?(result) result << match[1].scan(/.../).join(',') result << match.post_match unless match.post_match.nil? result end An alternative solution using a complex Regexp is: def threepack(x) return x unless x.class == String match = /^([-+]?)((\d{1,2})?)((\d{3})+)((\.\d+)?)$/.match(x) return x if match.nil? result = match[2].empty? ? match[1] : match[1] + match[2] + ',' result + match[4].scan(/.../).join(',') + match[6] end match[1] is the sign, match[2] is the digits before the three-digit blocks, match[4] is the concatenation of all three-digit blocks, match[6] is what follows the three-digit blocks. The strings are empty if the given part is absent. Josef 'Jupp' Schugt -- Damnant quod non intelligunt.