Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through the digits of an integer? [duplicate]

Tags:

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?

like image 769
Rivasa Avatar asked Oct 26 '12 17:10

Rivasa


People also ask

Can you iterate through integer?

Iterables in Python are objects and containers that could be stepped through one item at a time, usually using a for ... in loop. Not all objects can be iterated, for example - we cannot iterate an integer, it is a singular value.

How do you iterate through a digit in Python?

Method 1: Iterate through digits of a number in python using the iter() function. The first method to iterate through digits of a number is the use of iter() function. It accepts the string value as the argument. Therefore you have to first typecast the integer value and then pass it into it.


1 Answers

The shortest solution probably is:

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

A more orthodox mathematical approach:

class Integer   def digits(base: 10)     quotient, remainder = divmod(base)     quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder]   end end  0.digits #=> [0] 1234.digits #=> [1, 2, 3, 4] 0x3f.digits(base: 16) #=> [3, 15] 
like image 187
tokland Avatar answered Oct 12 '22 01:10

tokland