Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中有没有优雅的方法将数字转换成数字数组_Ruby_Arrays_String_Fixnum - Fatal编程技术网

在Ruby中有没有优雅的方法将数字转换成数字数组

在Ruby中有没有优雅的方法将数字转换成数字数组,ruby,arrays,string,fixnum,Ruby,Arrays,String,Fixnum,对于数字n,我只能想到 array_of_digits = n.to_s.split('').map(&:to_i) 还有更优雅的方法吗?不是更优雅,而是更快: def digits(n) (0..Math.log10(n).to_i).map { |dp| n / 10 ** dp % 10 }.reverse end 另一个我刚找到的最快的(最快的) 基准: user system total real Split ma

对于数字n,我只能想到

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

还有更优雅的方法吗?

不是更优雅,而是更快:

def digits(n)
  (0..Math.log10(n).to_i).map { |dp| n / 10 ** dp % 10 }.reverse
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)

顺便说一下,基准测试的代码在这里:

我认为split也很慢。想与
n.to#u.chars.map(&:to#i)
进行比较吗?是的,我会选择chars-one,它既快速又优雅,两个世界都是最好的。不过,数值让你有了一些见解(我希望
Fixnum#to#u
内部有类似之处)。不管怎样,答案都很好。@ItdoesNetwork的
每个字节
方法都很有趣,但我认为大多数Rubiests都会使用您拥有的方法,尽管我认为
字符串/u位=n.to\s。每个字符映射(&:to\u I)
都是一个小小的改进,因为它没有创建中间数组。
            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)