Link Link - 7 months ago 13
Ruby Question

How do I iterate through the digits of an integer?


Possible Duplicate:

Turning long fixed number to array Ruby




Well, I have to iterate over the digits of a integer in Ruby. Right now I was just splitting it up into an array, and then iterating over that. However I was wondering if there was a faster way to do this?

Answer

The shortest solution probably is:

1234.to_s.chars.map(&:to_i)
#=> [1, 2, 3, 4]

Here's a more orthodox mathematical approach:

class Fixnum
  def digits(base: 10)
    quotient, remainder = divmod(base)
    quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder]
  end
end

1234.digits #=> [1, 2, 3, 4]
0644.digits(base: 8) #=> [6, 4, 4]
0x3f.digits(base: 16) #=> [3, 15]