The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

5.6. Formatting Numbers with Commas

There may be better ways to do it, but this one works. We reverse the string to make it easier to do global substitution and then reverse it again at the end:

def commas(x) str = x.to_s.reverse str.gsub!(/([0-9]{3})/,"\\1,") str.gsub(/,$/,"").reverse end puts commas(123) # "123" puts commas(1234) # "1,234" puts commas(12345) # "12,435" puts commas(123456) # "123,456" puts commas(1234567) # "1,234,567"

Категории