如何在 Ruby 中输出前导零? [英] How can I output leading zeros in Ruby?

查看:45
本文介绍了如何在 Ruby 中输出前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Ruby 脚本输出一组编号文件.这些数字来自递增计数器,但为了使它们在目录中很好地排序,我想在文件名中使用前导零.换句话说

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...

file_001...

代替

文件_1

在将数字转换为字符串时,是否有一种简单方法来添加前导零?(我知道我可以做到如果少于 10 .... 如果少于 100").

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

推荐答案

如果已知计数器的最大位数(例如,对于计数器 1..876,n = 3),您可以这样做

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

这篇关于如何在 Ruby 中输出前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆