512 views
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]
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
The digits
method, which is available on integers, is used to obtain an array containing the digits of the number in reverse order.
result = 12345.digits # => [5, 4, 3, 2, 1]
is equivalent to
12345.to_s.chars.map(&:to_i).reverse # => [5, 4, 3, 2, 1]
The digits are listed in reverse order for convenience so you can start your iteration with the units digit (5
).
Indeed, [5, 4, 3, 2, 1]
indicates that the units digit is 5, the tens digit is 4, and so on.
The digits
method is a convenient way to break down an integer into its individual digits and represent them in an array.
This can be useful in scenarios where you need to work with individual digits, such as when manipulating or analyzing numbers in a specific way.
Voilà!
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©