For no particular reason, I am trying to add a #reverse method to the Integer class:
puts 1337.reverse # => 7331
puts 1000.reverse # => 1
This works fine except for numbers ending in a
0, as shown when
1 rather than
0001. Is there any way to keep leading zeroes when converting a string into an integer?
Best How To :
Short answer: no, you cant.
2.1.5 :001 > 0001
0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1.
Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case you are probably converting it into another kind of object (e.g a String).
If you want to keep the integer as
Fixnum you will not be able to add leading zeros.
The real question is: why do you want/need leading zeros? You didn't provide such information in the question. There are probably better ways to achieve your result (such as wrapping the value into a decorator object if the goal is to properly format a result for display).