Reputation: 6263
Is there a method in ruby that allows breaking integers up into 1s, 10s, 100s, 1000s, ...?
I know that you can convert an integer to a string and parse the string to get the values mentioned above, but I would imagine there is a really simple way to do this with ruby like most other things. So far I have this:
1234.to_s.chars.reverse.each_with_index
.map{|character, index| character.to_i * 10**index }
# => [4, 30, 200, 1000]
But is there something specific to do this in ruby?
Upvotes: 1
Views: 274
Reputation: 11313
def value_of_powers(number, base: 10)
number.to_s.reverse.each_char.with_index.map do |character, index|
base**index * character.to_i
end.reverse
end
value_of_powers(10212, base: 3) # => [81, 0, 18, 3, 2]
value_of_powers(1234) # => [1000, 200, 30, 4]
I reversed the order so that the values are read in the same order as we read numbers.
As shown, it also works for other base numbers. Given no base, it will default to base 10.
Upvotes: 1
Reputation: 110675
You could do that as follows:
n = 1020304
Math.log10(n).ceil.times.with_object([]) do |i,a|
n, d = n.divmod(10)
a << d * 10**i
end
#=> [4, 0, 300, 0, 20000, 0, 1000000]
Hmmm. That looks a bit odd. Maybe it would be better to return a hash:
Math.log10(n).ceil.times.with_object({}) do |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}
Upvotes: 2
Reputation: 7203
This isn't particularly clever, but I suppose it's relatively clear about what it does.
def tens_places(n, place = 1)
if n >= 1
[(n % 10).floor * place] + tens_places(n/10, place * 10)
else
[]
end
end
Upvotes: 0