How to convert an array of digits to a number in Ruby

1 Answer

0 votes
# ------------------------------------------------------------
# join_digits
# Treats the array as digits and concatenates them into a number.
# Example: [1,2,3,4] → 1234
# ------------------------------------------------------------
def join_digits(arr)
  arr.join.to_i
end
 
# ------------------------------------------------------------
# fold_digits
# Pure mathematical folding (no string conversion).
# Example: [1,2,3,4] → 1234
# ------------------------------------------------------------
def fold_digits(arr)
  arr.reduce(0) { |acc, d| acc * 10 + d }
end
 
# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------
digits = [1, 2, 3, 4]
 
puts "Array of digits: #{digits.inspect}"
puts "join_digits:  #{join_digits(digits)}"
puts "fold_digits:  #{fold_digits(digits)}"
 
 
 
# run:
#
# Array of digits: [1, 2, 3, 4]
# join_digits:  1234
# fold_digits:  1234
# 
 
 

 



answered May 10 by avibootz
edited May 10 by avibootz
...