Reputation: 14227
As you know in ruby you can do
"%03d" % 5
#=> "005"
"%03d" % 55
#=> "055"
"%03d" % 555
#=> "555"
so basically number will have "0" prefix for 3 string places
just wondering is there possibility to do number string suffix in similar nice way ? (please no if statements)
something 5
#=> 500
something 55
#=> 550
something 555
# => 555
Upvotes: 5
Views: 960
Reputation: 30765
How about
def prettify(n)
("%03d" % (n.to_s.reverse.to_i)).to_s.reverse
end
which
Maintaining this piece of code might become a challenge a few months from now, of course :-)
Upvotes: 0
Reputation: 8094
how about ljust method?
"5".ljust(3, "0")
and some to_s
and to_i
method calls if you want to do that to integers
you could avoid string conversion with bit more math like log_10
to find number of digits in an integer and then i *= 10**x
where x
is how many more 0's you need
like this:
def something(int, power=3)
int * 10**([power - Math.log10(int).to_i - 1, 0].max)
end
Upvotes: 7