1. Computing
Michael Morin

A Quick Peek at Ruby: Large Number Literals

By September 3, 2008

Follow me on:

Now and again there may be things you want to know about Ruby that don't take a whole lot of explanation. Of course, this doesn't mean they aren't interesting, just that they don't warrant an entire article or tutorial. For this purpose keep an eye out for "Quick Peek at Ruby" blog posts. Today's topic is Large Number Literals.

Ruby has a special syntax for representing large numbers in literals. The number 1000000 is ambiguous, it's difficult to tell at a glance how many zeros there are. The comma separator cannot be used since it's already used as a list separator. 1,000,000 would be a list of 3 numbers. Ruby number literals can use the underscore character as a place separator, so 1000000 can be better represented as 1_000_000.

Note that there are no rules as to where the underscores can appear within the number. The 3 digit grouping convention can be ignored, which can lead to misleading number literals. Take a look at the following code:

$ irb
irb(main):001:0> a = 1_000_000
=> 1000000
irb(main):002:0> b = 1_0_0_0_0_0_0
=> 1000000

Need a quick peek at something Ruby? Send your question via email to your friendly Ruby Guides!

Comments
No comments yet. Leave a Comment
Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>
Top Related Searches
  • peek
  • ruby
    1. About.com
    2. Computing
    3. Ruby

    ©2014 About.com. All rights reserved.