Turning long fixed number to array Ruby
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]
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
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
Maybe not the most elegant solution:
74239.to_s.split('').map(&:to_i)
Output:
[7, 4, 2, 3, 9]