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) }
1.upto(134) { |i| printf("%03d\n", i) }(1..134).each(&method(:printf).curry(2).call("%03d\n"))% operator is here: String#%. The format string is specified in Kernel#sprintf, of which Kernel#format is an alias.
('001'..'134').each { |s| puts s }#uptoe.g.'001'.upto('134')puts [*'001'..'134']