I'd like for this script
(1..134).each do |x|
puts "0#{x}" # ????
end
to output:
001
002
...
011
...
134
Is this possible without doing a bunch of if statements using just native format? It doesn't need to handle greater than 3 digits.
One way to achieve the zero padding you want is to use #rjust:
(1..134).each do |x|
puts x.to_s.rjust(3, '0')
end
Hope this helps!
Sure. It can be done using the following formatter:
'%03d' % 1 # 001
'%03d' % 10 # 010
'%03d' % 100 # 100
The loop is going to look like this:
(1..134).each { |x| puts '%03d' % x }
There's also Kernel#format method, which does exactly this, but self-explanatory:
(1..134).each { |x| puts format('%03d', x) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With