Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Ruby string to 3 characters with an integer

Tags:

ruby

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.

like image 898
timpone Avatar asked Dec 22 '25 10:12

timpone


2 Answers

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!

like image 188
Zoran Avatar answered Dec 24 '25 01:12

Zoran


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) }
like image 32
Igor Drozdov Avatar answered Dec 24 '25 01:12

Igor Drozdov



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!