Today’s topic is the following rule from the Ruby Style Guide:
Add underscores to large numeric literals to improve their readability.
Most of the programs we write feature a substantial number of numeric
0xCAFE). There is nothing
strange or unusual about that. From time to time, however, those literals are pretty long:
1 2 3
I’m pretty sure most of you would have pretty hard time to quickly
digest a number written in this way – lots of digits and no separators
between them to help us discern the number’s
structure. At this
_ makes a dramatic appearance and comes to the rescue:
1 2 3
The addition of a few
_ improves the readability of those huge literals a ton!
The underscores we add to numeric literals are ignored by
As you can see from the preceding example nothing’s lost or changed – we’ve only gained readability and eased the parsing burden on our brains.
Obviously we should not overdo
1 2 3 4 5 6
Personally, when dealing with decimal literals, I tend to use
numbers with at 5 least digits(e.g.
11_948). The number of digits to separate with
_ depends on the numeric base – in decimal it makes sense to group
digits by 3(
1_000_000), in binary by 4(
That’s all for today folks! Hope I managed to convince at least a few of you of the benefits of using underscores in your long numeric literals.
As usual I’m looking forward to hearing your thoughts here and on Twitter!