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.

567321.digits
#=> [1, 2, 3, 7, 6, 5]

567321.digits[3]
#=> 7

We can also supply a different base as an argument.

0123.digits(8)
#=> [3, 2, 1]

0xabcdef.digits(16)
#=> [15, 14, 13, 12, 11, 10]

Use case of digits

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

123.to_s.chars.map(&:to_i).sum
#=> 6

123.digits.sum
#=> 6

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