BigBinary Blog

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

Ruby 2.4 Integer#digits extract digits in place-value

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.

Rohit Kumar in Ruby 2.4
February 23, 2017
Share

Subscribe to our newsletter