Ruby 2.4 Integer#digits extract digits in place-value

Rohit Kumar

By Rohit Kumar

on February 23, 2017

This blog is part of our  Ruby 2.4 series.

If we want to extract all the digits of an integer from right to left, the newly added Integer#digits method will come in handy.

1
2567321.digits
3#=> [1, 2, 3, 7, 6, 5]
4
5567321.digits[3]
6#=> 7
7

We can also supply a different base as an argument.

1
20123.digits(8)
3#=> [3, 2, 1]
4
50xabcdef.digits(16)
6#=> [15, 14, 13, 12, 11, 10]
7

Use case of digits

We can use Integer#digits to sum all the digits in an integer.

1
2123.to_s.chars.map(&:to_i).sum
3#=> 6
4
5123.digits.sum
6#=> 6
7

Also while calculating checksums like Luhn and Verhoeff, Integer#digits will help in reducing string allocation.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.