Last active
May 26, 2023 15:18
-
-
Save knugie/4168392 to your computer and use it in GitHub Desktop.
Format Ruby Integers with underscore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# <#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