Leslie Viljoen
12/13/2005 5:25:00 PM
Hiya!
This function adds commas to a string after every three characters
so a number would be easier to read. It's kinda ugly though, and I can't
help thinking there'd be a elegant Why-esque one or two liner to do
this kind of thing - anyone care to improve it?
def add_commas(str)
return nil if str.class != String
ret = ""
len = str.length
i = len - 1
while i >= 0
ret = str[i].chr + ret
if ((len-i) % 3) == 0
ret = "," + ret
end
i -= 1
end
if ret[0].chr == ","
ret = ret[1..-1]
end
ret
end