How can I output leading zeros in Ruby?

前端 未结 6 370
攒了一身酷
攒了一身酷 2021-01-29 18:31

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

6条回答
  •  醉梦人生
    2021-01-29 19:23

    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")
    

提交回复
热议问题