【问题标题】:Is there any elegant method in Ruby to convert a number to an array of digitsRuby中是否有任何优雅的方法可以将数字转换为数字数组
【发布时间】:2015-04-12 17:47:19
【问题描述】:

对于数字n,我只能想到

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

还有更优雅的方法吗?

【问题讨论】:

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

标签: ruby arrays string fixnum


【解决方案1】:

不是更优雅,而是更快:

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

【讨论】:

  • 我在想 split 也很慢。 . .想和n.to_s.chars.map(&:to_i)比较?
  • 是的,我会选择 chars 的,它既快速又优雅,两全其美。
  • Numerical 给你一些洞察力(我希望Fixnum#to_s 内部有类似的东西)。无论哪种方式都很好。
猜你喜欢
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多