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]
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.

Written byRohit Kumar
Related blogs
- 01Ruby 2.4 has optimized enumerable min max methodsSeptember 28, 2017 · Chirag Shah
- 02CSV::Row#each etc. return enumerator when no block givenSeptember 25, 2017 · Sushant Mittal
- 03Ruby 2.4 DateTime#to_time & Time#to_time keeps infoSeptember 19, 2017 · Sushant Mittal
- 04Avoid exception for dup on IntegerAugust 1, 2017 · Rohit Arolkar