Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format integer to string with fixed length in Ruby

Is there a easy way to format a given Integer to a String with fixed length and leading zeros?

# convert numbers to strings of fixed length 3 
[1, 12, 123, 1234].map { |e| ??? }
=> ["001", "012", "123", "234"]

I found a solution but maybe there is a smarter way.

format('%03d', e)[-3..-1]
like image 622
sschmeck Avatar asked Nov 06 '15 09:11

sschmeck


1 Answers

How about getting the last three digits using % 1000 instead of doing string manipulations?

[1, 12, 123, 1234].map { |e| format('%03d', e % 1000) }

Update:

As suggested by the Tin Man in the comments, the original version is better in terms of readability and only abount 1.05x slower than this one, so in most cases it probably makes sense to use that.

like image 83
Cristian Lupascu Avatar answered Nov 14 '22 23:11

Cristian Lupascu