4

For number n, I could only think of

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

Is there any more elegant method?

doge
  • 132
  • 1
  • 8
  • @itdoesntwork's `each_byte` method is interesting, but I think most Rubiests would go with what you have, though I think `string_of_digits = n.to_s.each_char.map(&:to_i)` is a small improvement because it doesn't create an intermediate array. – Cary Swoveland Apr 12 '15 at 19:13

1 Answers1

6

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

itdoesntwork
  • 4,666
  • 3
  • 25
  • 38