2

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.

3
  • 5
    FYI, Ruby can also iterate numerical strings: ('001'..'134').each { |s| puts s } Commented Apr 26, 2018 at 18:58
  • What @Stefan said although I prefer the readability and ephemeral nature of #upto e.g. '001'.upto('134') Commented Apr 26, 2018 at 19:01
  • What @Stefan said, modified puts [*'001'..'134'] Commented Apr 26, 2018 at 21:11

2 Answers 2

5

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!

Sign up to request clarification or add additional context in comments.

Comments

3

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) }

4 Comments

This works but it's going to be completely mystifying to a novice who wants to know how it works.
Alternatively: 1.upto(134) { |i| printf("%03d\n", i) }
@JordanRunning where is @mudasobwa to pull out a (1..134).each(&method(:printf).curry(2).call("%03d\n"))
The documentation for the % operator is here: String#%. The format string is specified in Kernel#sprintf, of which Kernel#format is an alias.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.