How can I output leading zeros in Ruby?

Ruby

Ruby Problem Overview


I'm outputting a set of numbered files from a Ruby script. The numbers come from incrementing a counter, but to make them sort nicely in the directory, I'd like to use leading zeros in the filenames. In other words

> file_001...

instead of

> file_1

Is there a simple way to add leading zeros when converting a number to a string? (I know I can do "if less than 10.... if less than 100").

Ruby Solutions


Solution 1 - Ruby

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Solution 2 - Ruby

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")

Solution 3 - Ruby

Can't you just use string formatting of the value before you concat the filename?

"%03d" % number

Solution 4 - Ruby

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

Solution 5 - Ruby

As stated by the other answers, "%03d" % number works pretty well, but it goes against the rubocop ruby style guide:

> Favor the use of sprintf and its alias format over the fairly cryptic String#% method

We can obtain the same result in a more readable way using the following:

format('%03d', number)

Solution 6 - Ruby

filenames = '000'.upto('100').map { |index| "file_#{index}" }

Outputs

[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan LongView Question on Stackoverflow
Solution 1 - RubyDaniel MartinView Answer on Stackoverflow
Solution 2 - Rubyalex.zherdevView Answer on Stackoverflow
Solution 3 - RubyÓlafur WaageView Answer on Stackoverflow
Solution 4 - RubytestrView Answer on Stackoverflow
Solution 5 - RubyRodrigo VasconcelosView Answer on Stackoverflow
Solution 6 - RubyIvanView Answer on Stackoverflow