nne*_*neo 16
也许不是最优雅的解决方案:
74239.to_s.split('').map(&:to_i)
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 4, 2, 3, 9]
Run Code Online (Sandbox Code Playgroud)
对于这类事情,您不需要通过字符串陆地进行往返:
def digits(n)
Math.log10(n).floor.downto(0).map { |i| (n / 10**i) % 10 }
end
ary = digits(74239)
# [7, 4, 2, 3, 9]
Run Code Online (Sandbox Code Playgroud)
这确实假设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
Run Code Online (Sandbox Code Playgroud)
从 Ruby 2.4 开始,整数(FixNum在 2.4+ 中消失了)有一个内置digits方法,可以将它们提取到数字数组中:
74239.digits
=> [9, 3, 2, 4, 7]
Run Code Online (Sandbox Code Playgroud)
如果你想保持数字的顺序,只需链接reverse:
74239.digits.reverse
=> [7, 4, 2, 3, 9]
Run Code Online (Sandbox Code Playgroud)
文档:https://ruby-doc.org/core-2.4.0/Integer.html#method-i-digits
divmod方法可用于一次提取一个数字
def digits n
n= n.abs
[].tap do |result|
while n > 0
n,digit = n.divmod 10
result.unshift digit
end
end
end
Run Code Online (Sandbox Code Playgroud)
快速基准测试表明,这比使用日志提前查找数字更快,这本身比基于字符串的方法更快.
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)
Run Code Online (Sandbox Code Playgroud)
您可以转换为字符串并使用 chars 方法:
74239.to_s.chars.map(&:to_i)
Run Code Online (Sandbox Code Playgroud)
输出:
[7, 4, 2, 3, 9]
Run Code Online (Sandbox Code Playgroud)
它比拆分更优雅。