将长固定数转换为数组 Ruby [英] Turning long fixed number to array Ruby
本文介绍了将长固定数转换为数组 Ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ruby 有没有办法把74239
这样的fixnum 变成[7,4,2,3,9]
这样的数组?
Is there a method in ruby to turn fixnum like 74239
into an array like [7,4,2,3,9]
?
推荐答案
你不需要为这种事情来回走一趟:
You don't need to take a round trip through string-land for this sort of thing:
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
放入混合中可以解决这个问题.如果您需要覆盖非正值,则:
This does assume that n
is positive of course, slipping an n = n.abs
into the mix can take care of that if needed. If you need to cover non-positive values, then:
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
这篇关于将长固定数转换为数组 Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文