Skip to content

Instantly share code, notes, and snippets.

@knugie
knugie / integer_underscore.rb
Last active May 26, 2023 15:18
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_")