How can I output leading zeros in Ruby?

前端 未结 6 374
攒了一身酷
攒了一身酷 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:12

    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.

提交回复
热议问题