<分区>
Possible Duplicate:
Turning long fixed number to array Ruby
好吧,我必须在 Ruby 中迭代整数的数字。现在我只是将它拆分成一个数组,然后对其进行迭代。但是我想知道是否有更快的方法来做到这一点?
<分区>
Possible Duplicate:
Turning long fixed number to array Ruby
好吧,我必须在 Ruby 中迭代整数的数字。现在我只是将它拆分成一个数组,然后对其进行迭代。但是我想知道是否有更快的方法来做到这一点?
最佳答案
最短的解决方案可能是:
1234.to_s.chars.map(&:to_i)
#=> [1, 2, 3, 4]
更正统的数学方法:
class Integer
def digits(base: 10)
quotient, remainder = divmod(base)
quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder]
end
end
0.digits #=> [0]
1234.digits #=> [1, 2, 3, 4]
0x3f.digits(base: 16) #=> [3, 15]
关于ruby - 如何遍历整数的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13091558/