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?
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With