---
title: "Ruby 2.4 Integer#digits extract digits in place-value"
description:
  "Ruby 2.4 implements Integer#digits for extracting digits in place-value
  notation which is useful in calculating checksum digits."
canonical_url: "https://www.bigbinary.com/blog/ruby-2-4-implements-integer-digits-for-extracting-digits-in-place-value-notation"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-4-implements-integer-digits-for-extracting-digits-in-place-value-notation.md"
---

# Ruby 2.4 Integer#digits extract digits in place-value

Ruby 2.4 implements Integer#digits for extracting digits in place-value notation
which is useful in calculating checksum digits.

- Author: Rohit Kumar
- Published: February 23, 2017
- Categories: Ruby 2.4, Ruby

If we want to extract all the digits of an integer
[from right to left](https://en.wikipedia.org/wiki/Positional_notation), the
newly added [Integer#digits](https://bugs.ruby-lang.org/issues/12447) method
will come in handy.

```ruby

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

567321.digits[3]
#=> 7

```

We can also supply a different base as an argument.

```ruby

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.

```ruby

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

123.digits.sum
#=> 6

```

Also while calculating checksums like
[Luhn](https://en.wikipedia.org/wiki/Luhn_algorithm) and
[Verhoeff](https://en.wikipedia.org/wiki/Verhoeff_algorithm), `Integer#digits`
will help in reducing string allocation.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-4-implements-integer-digits-for-extracting-digits-in-place-value-notation)
