Integer#digits returns the digits in reverse
Question
What's the return value of the following Ruby code?
12345.digits # => ???
The correct answer is
-
["1", "2", "3", "4", "5"] -
[1, 2, 3, 4, 5] -
["5", "4", "3", "2", "1"] -
[5, 4, 3, 2, 1]Correct
Explanation
TL;DR
Integer#digits returns the digits of the receiver as an array of integers, least significant digit first. 12345.digits returns [5, 4, 3, 2, 1]: the units digit 5 at index 0, the tens digit 4 at index 1, and so on.
Step by step
12345.digits # => [5, 4, 3, 2, 1]
A rough string-based equivalent:
12345.to_s.chars.map(&:to_i).reverse # => [5, 4, 3, 2, 1]
The reversed order is not an accident. It makes the index meaningful: digits[i] is the coefficient of 10**i, so the place value of each digit is encoded in its position. That also makes the number trivial to reconstruct:
d = 12345.digits
d.each_with_index.sum { |digit, i| digit * 10**i } # => 12345
And the units digit is simply first, without knowing the number's length:
12345.digits.first # => 5
12345 % 10 # => 5
Edge cases
digits accepts a base. The result is the positional representation in that base, still least significant first:
255.digits(16) # => [15, 15]
255.digits(2) # => [1, 1, 1, 1, 1, 1, 1, 1]
0.digits # => [0]
Negative numbers have no well-defined digit expansion, so digits raises:
begin
-123.digits
rescue Math::DomainError => e
e.message # => "out of domain"
end
digits is defined on Integer only; call to_i first if you are starting from a Float.
Share this quiz
Comments
No comments yet. Be the first.