Reverse integer digits

ruby

Solution

This is a very "code golf"-ish answer, and not something I'd suggest writing in real code...

But you can shave an extra character off the answer with:

123456.to_s.reverse.to_i
123456.digits.join.to_i

Or (again, only as a 'code golf' answer!!) if you're happy to end up with a `String` rather than an `Integer`, you can make this even sorter with:

123456.digits*''  #=> "654321"

In fact, converting to a string might actually be preferable, because it may prevent loosing information from missing zeros. Code-golf answers aside, compare:

43210.to_s.reverse #=> "01234"
43210.to_s.reverse.to_i #=> 1234

Problem

I was trying to reverse the digits of an integer: `123456 => 654321`, and the best solution that I could come up with was `123456.to_s.reverse.to_i`. I feel that this is too much of code. Anyone have a better approach than this?

Original source