I am interating through |f|
f.print "ITEM", i
ITEM001
ITEM002
....
ITEM044
....
ITEM745
How can I define i so that if i is 1 it will print 001 always making sure there are three digits?
It's called padding:
5.times do |x|
puts "ITEM%03d" % x
end
# >> ITEM000
# >> ITEM001
# >> ITEM002
# >> ITEM003
# >> ITEM004
Or alternatively
5.times do |x|
puts "ITEM" + x.to_s.rjust(3, '0')
end
I like to use printf for this kinds of job, it's flexible enough and easy to remember.
5.times do |x|
printf("ITEM%03d\t", x)
end
#ITEM000 ITEM001 ITEM002 ITEM003 ITEM004
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