Separating integer values into an array

143 Views Asked by At

Is there an equivalent of the String chars method for fixnum? Am trying to separate an integer value by value into an array e.g. 1234 -> [1, 2, 3, 4] to then perform operations on the individual values.

Or is it better to convert into a string first, perform an operation (example x 2) and then join as integers? Like below:

    def method_name num
      num.to_s.chars.map{|x| x.to_i*2}.join.to_i
    end
1

There are 1 best solutions below

5
Dave Newton On

There's nothing that splits a number into individual digits, since that's generally a nonsense thing to do with a number. You could also do it the math-y way, but I don't see a distinct advantage to doing so given the requirements (so far).

I might prefer to split the conversion and multiplication, e.g.,

n.to_s.chars.map(&:to_i).map { |n| n * 2 }.join.to_i

It's a bit more versatile, and if, say, your multiplier changes, it's easy to change (not shown here, but there are ways).