How can I output leading zeros in Ruby?

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

    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
    

提交回复
热议问题