ruby - How to get 10s, 100s, 1000s from an integer? -
is there method in ruby allows breaking integers 1s, 10s, 100s, 1000s, ...?
i know can convert integer string , parse string values mentioned above, imagine there simple way ruby other things. far have this:
1234.to_s.chars.reverse.each_with_index .map{|character, index| character.to_i * 10**index } # => [4, 30, 200, 1000]
but there specific in ruby?
you follows:
n = 1020304 math.log10(n).ceil.times.with_object([]) |i,a| n, d = n.divmod(10) << d * 10**i end #=> [4, 0, 300, 0, 20000, 0, 1000000]
hmmm. looks bit odd. maybe better return hash:
math.log10(n).ceil.times.with_object({}) |i,h| n, d = n.divmod(10) h[10**i] = d end #=> {1=>4, 10=>0, 100=>3, 1000=>0, 10000=>2, 100000=>0, 1000000=>1}
Comments
Post a Comment