In Ruby, you can convert an array of digits to an integer in the following ways:
Looping, Shifting and Adding Digits to the Right
To convert an array of digits to an integer, you can use the Enumerable#inject
method (or its alias Enumerable#reduce
), in the following way:
array.inject(0) { | memo, digit | memo * 10 + digit }
Passing 0
as the initial operand (or base case) is important as nil
would be returned for empty arrays otherwise.
This works in the following way:
- An accumulator/memo value is passed to the block (as the first argument), which contains the result of the calculation of previous iteration;
- By multiplying the "accumulated" (memo) value by
10
, each value in the array is widened to the right, to which then the current digit is added. This results in each digit in the array being added to the resulting integer one by one; - At the end of the iteration, the final (single/reduced) value of accumulator/memo is returned.
For example:
num = [1, 2, 3, 4, 5].inject(0) { | memo, digit | memo * 10 + digit } puts num #=> 12345 puts num.class #=> Integer
This can be visualized like so:
# Iteration#1 (memo = 0, digit = 1) => 0 * 10 + 1 = 1 # Iteration#2 (memo = 1, digit = 2) => 1 * 10 + 2 = 12 # Iteration#3 (memo = 12, digit = 3) => 12 * 10 + 3 = 123 # Iteration#4 (memo = 123, digit = 4) => 123 * 10 + 4 = 1234 # Iteration#5 (memo = 1234, digit = 5) => 1234 * 10 + 5 = 12345 # Iteration#6 (memo = 12345, digit = nil) => 12345
Convert Array to String and Then to Integer
You can use the Array#join
method to convert an array to a string, and then call String#to_i
to convert the resulting string to an integer:
array.join.to_i
For example:
num = [1, 2, 3, 4, 5].join.to_i puts num #=> 12345 puts num.class #=> Integer
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.