you convert x to a string and using split to cut it to array.
example:
x = 1234
=> x.to_s.split("")
result to run it: [“1”, “2”, “3”, “4”]
ruby -e “a=123405; r=; (r.unshift(a%10) ; a/=10 ) while a>0; p r”
require 'benchmark'
def dec1(a)
r=[]
(r.unshift(a%10) ; a/=10 ) while a>0
r
end
def dec2(a)
a.to_s.split(//).map(&:to_i)
end
X=10000
Benchmark.bm do |x|
x.report("arithmetics") { X.times {|i| dec1(11223344556677889900+i)} }
x.report("string size") { X.times {|i| dec2(11223344556677889900+i)} }
end
>ruby a.rb
user system total real
arithmetics 0.062000 0.000000 0.062000 ( 0.067551)
string size 0.156000 0.000000 0.156000 ( 0.170436)
2.3.3 :003 > x = 1234
=> 1234
2.3.3 :004 > x.to_s.split('').map(&:to_i)
=> [1, 2, 3, 4]
number.to_s.chars.map(&:to_i) # before ruby 2.4
number.digits # after ruby 2.4
you can do like:
1234.to_s.chars.map(&:to_i)
=> [1, 2, 3, 4]