-1

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
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Ok, apparently can be done without conversion to string: `Math.log10(1234).floor.downto(0).map { |i| (1234 / 10**i) % 10 }` #=> [1, 2, 3, 4] – Andrey Deineko Dec 15 '16 at 15:24
  • @AndreyDeineko: yeah, I meant something like that :) – Sergio Tulentsev Dec 15 '16 at 15:25
  • @SergioTulentsev I'd never even think of using something like this.. Do you think it makes any sense in terms of efficiency (or in any terms :))? – Andrey Deineko Dec 15 '16 at 15:26
  • 1
    @AndreyDeineko: efficiency is to be measured, but sometimes stringification is not available (in other languages, I mean), whereas this math-based approach always works. So it is useful to be aware of this one weird trick :) – Sergio Tulentsev Dec 15 '16 at 15:28

1 Answers1

0

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).

Dave Newton
  • 158,873
  • 26
  • 254
  • 302