rubyarraysstringfixnum

Is there any elegant method in Ruby to convert a number to an array of digits


For number n, I could only think of

array_of_digits = n.to_s.split('').map(&:to_i)

Is there any more elegant method?


Solution

  • Not more elegant, but faster:

    def digits(n)
      (0..Math.log10(n).to_i).map { |dp| n / 10 ** dp % 10 }.reverse
    end
    

    Another fast one I just found (fastest)

    def digits(n)
      n.to_s.each_byte.map { |x| x - 48 }
    end
    

    Benchmarks:

                user     system      total        real
    Split map  0.410000   0.000000   0.410000 (  0.412397)
    chars      0.100000   0.010000   0.110000 (  0.104450)
    each byte  0.070000   0.000000   0.070000 (  0.068171)
    Numerical  0.100000   0.000000   0.100000 (  0.101828)
    

    The code for benchmarking is here, by the way: https://gist.github.com/sid-code/9ad26dc4b509bfb86810