Is there a method in ruby to turn fixnum like 74239
into an array like [7,4,2,3,9]
?
Turning long fixed number to array Ruby
13.9k views Asked by Ilya Nikiforov At
7
There are 7 answers
0
On
The divmod method can be used to extract the digits one at a time
def digits n
n= n.abs
[].tap do |result|
while n > 0
n,digit = n.divmod 10
result.unshift digit
end
end
end
A quick benchmark showed this to be faster than using log to find the number of digits ahead of time, which was itself faster than string based methods.
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)
0
On
As of Ruby 2.4, integers (FixNum
is gone in 2.4+) have a built-in digits
method that extracts them into an array of their digits:
74239.digits
=> [9, 3, 2, 4, 7]
If you want to maintain the order of the digits, just chain reverse
:
74239.digits.reverse
=> [7, 4, 2, 3, 9]
Docs: https://ruby-doc.org/core-2.4.0/Integer.html#method-i-digits
You don't need to take a round trip through string-land for this sort of thing:
This does assume that
n
is positive of course, slipping ann = n.abs
into the mix can take care of that if needed. If you need to cover non-positive values, then: