Ruby中的字符串长度修改

时间:2017-04-10 12:26:47

标签: ruby string

如何将字符串长度固定为10,即输入字符串总是小于或等于10个字符。如果它少于10个字符,我必须在字符串的开头添加0。

输入示例:

123456
1234567

需要输出:

0000123456
0001234567

输入是任意的。

提前致谢!

2 个答案:

答案 0 :(得分:6)

String#rjust就是这样做的:

'1234567'.rjust(10, '0') # => "0001234567"

答案 1 :(得分:1)

a = "123456"
b = "1234567"

"0"*(10-a.size)+a
=> "0000123456"
"0"*(10-b.size)+b
=> "0001234567"

有趣的是出于速度目的:

a = "123456"
n = 50000
Benchmark.bm do |x|
  x.report{n.times do ; a.rjust(10,'0'); end}
  x.report{n.times do ; "0"*(10-a.size)+a; end}
end
       user     system      total        real
   0.020000   0.000000   0.020000 (  0.016442)
   0.010000   0.000000   0.010000 (  0.015134)

或更高的样本量:

irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> a = "123456"
=> "123456"
irb(main):003:0> n = 5_000_000
=> 5000000
irb(main):004:0> Benchmark.bm do |x|
irb(main):005:1*   x.report{n.times do ; a.rjust(10,'0'); end}
irb(main):006:1>   x.report{n.times do ; "0"*(10-a.size)+a; end}
irb(main):007:1> end
       user     system      total        real
   1.510000   0.000000   1.510000 (  1.519720)
   1.480000   0.000000   1.480000 (  1.486935)