Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding integers in Ruby

Tags:

ruby

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?

like image 832
Bruno Avatar asked Mar 27 '26 16:03

Bruno


2 Answers

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
like image 91
Sergio Tulentsev Avatar answered Mar 29 '26 07:03

Sergio Tulentsev


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
like image 24
Yu Hao Avatar answered Mar 29 '26 05:03

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!