Skip to content

Instantly share code, notes, and snippets.

@knugie
Last active May 26, 2023 15:18
Show Gist options
  • Save knugie/4168392 to your computer and use it in GitHub Desktop.
Save knugie/4168392 to your computer and use it in GitHub Desktop.
Format Ruby Integers with underscore
# <#Integer>.underscore(n) returns a string, seperating n digits by
# an underscore. n is 3 by default. This is supposed to make
# working with large numbers easier.
# example:
# 1000000000000000.underscore #=> "1_000_000_000_000_000"
# 100_00000_00_0000_00.underscore #=> "1_000_000_000_000_000"
# 987654321.underscore(6) #=> "987_654321"
class Integer
def underscore(s=3)
self.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1_")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment