2015-04-12 29 views
4

对于数n的数组,我只能想到是否有任何的Ruby优雅的方法将数字转换为数字

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

是否有更优雅的方法是什么?

+0

@ itdoesntwork的'each_byte'方法很有意思,但我认为大多数Rubiests会和你所拥有的一样,尽管我认为'string_of_digits = n.to_s.each_char.map(&:to_i)'是一个小改进,因为它没有创建一个中间数组。 –

回答

6

不是更优雅,但速度更快:

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

另一个快一个我刚刚发现(最快)

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

基准:

  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) 

基准测试的代码是在这里,顺便说一下:https://gist.github.com/sid-code/9ad26dc4b509bfb86810

+2

我在想分裂也很慢。 。 。想与'n.to_s.chars.map(&:to_i)'进行比较? –

+0

我会编辑答案,包括那一个 – itdoesntwork

+0

是的,我会去的字符之一,它是快速和优雅,两全其美。 – itdoesntwork

相关问题