将长固定数转换为数组Ruby

在ruby中有一种方法可以将像74239这样的74239变成像[7,4,2,3,9]这样的数组吗?

对于这类事情,你不需要通过string-land进行往返:

 def digits(n) Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 } end ary = digits(74239) # [7, 4, 2, 3, 9] 

这确实假设n当然是正的,如果需要,将n = n.abs滑入混合可以处理。 如果您需要涵盖非正值,那么:

 def digits(n) return [0] if(n == 0) if(n < 0) neg = true n = n.abs end a = Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 } a[0] *= -1 if(neg) a end 

也许不是最优雅的解决方案:

 74239.to_s.split('').map(&:to_i) 

输出:

 [7, 4, 2, 3, 9] 

divmod方法可用于一次提取一个数字

 def digits n n= n.abs [].tap do |result| while n > 0 n,digit = n.divmod 10 result.unshift digit end end end 

快速基准测试显示,这比使用日志提前查找数字更快,这本身比基于字符串的方法更快。

 bmbm(5) do |x| x.report('string') {10000.times {digits_s(rand(1000000000))}} x.report('divmod') {10000.times {digits_divmod(rand(1000000000))}} x.report('log') {10000.times {digits(rand(1000000000))}} end #=> user system total real string 0.120000 0.000000 0.120000 ( 0.126119) divmod 0.030000 0.000000 0.030000 ( 0.023148) log 0.040000 0.000000 0.040000 ( 0.045285) 

您可以转换为字符串并使用chars方法:

 74239.to_s.chars.map(&:to_i) 

输出:

 [7, 4, 2, 3, 9] 

它比分裂更优雅。

您也可以使用Array.new而不是map

 n = 74239 s = Math.log10(n).to_i + 1 # Gets the size of n Array.new(s) { d = n % 10; n = n / 10; d }.reverse 

在Ruby 2.4中,整数将有一个数字方法 。