Quick! How many zeroes are in this number?
1000000000000000
Time’s up! Did you get it right?
Large literal numbers may be a cinch for the computer to read, but they aren’t very friendly to human eyes. In this very short screencast, you’ll learn how Ruby makes it easy to write pretty, readable numbers in your code.
Continuing in this series about literals and quoting, let’s talk about large integers.
Quick question: how many zeroes are in this number?
100000000000
Past a certain size, it’s hard to visually identify the number of digits in a numeric literal. That’s why in written language we usually break the number into groups of digits. For instance, in my US locale we would normally split the number into groups of three digits, with commas:
# 100,000,000,000
Thankfully, we can do something similar in Ruby. Ruby lets us insert underscores anywhere we want in integer literals. So we could rewrite this number like so:
100_000_000_000
And I think you’ll agree that’s a lot easier to visually parse.
That’s all for today. Happy hacking!
Avdi — I’ve been beating this same drum for years about comma-separating big numbers for readability! My own Ruby eva-luator does this by default:
$ eva “2**64”
18,446,744,073,709,551,616
not this(!):
$ eva “2**64” –format=bare
18446744073709551616
I wrote a method “thousands()” early in my Ruby learning, and it’s just a wrapper for a more general “groupsep()” method which can group arbitrary group-lengths with arbitrary separator characters, e.g.
“00306EF30B4F”.groupsep( grp=2, sep=’-‘ ) # ==> “00-30-6E-F3-0B-4F”
so method “thousands” is essentially:
18446744073709551616.groupsep( 3, ‘,’ ) # ==> “18,446,744,073,709,551,616”
(and yes, both thousands and groupsep handle both String and Integer classes).
A couple of fun, very useful methods, part of a slightly larger module/library. Let’s hear it for properly comma-separated, readable large numbers! And yes, underscore-formatting is great for source-code/literal big-ints, but I found that output formatting is the real use-case, and yes, you could use an ‘_’ in groupsep for that output too! 😉
— Lorin
I’m curous about eva; is there more info about it somewhere?
—