Search code examples
arraysrubysortinginteger-arithmetic

How to: multiple-digit integer, extract each integer into an array of single integers


I'm undertaking an exercise that hinges on being able to do this task. I have to take a multiple digit integer >=0, i.e. 830124, and make an array of the individual digits.

My line of thinking is that I can convert it to a string, index the string in an array, then convert back to ints, but i'm still a little lost. Any suggestions?


Solution

  • n = 830124
    
    n.to_s.split('').map(&:to_i)
      #=> [8, 3, 0, 1, 2, 4]
    

    or, without converting characters to integers:

    n.to_s.size.times.with_object([]) { |_,a| n,i = n.divmod(10); a.unshift(i) }
      #=> [8, 3, 0, 1, 2, 4]