6

I have a set of filenames named like the following

"file001" "file0001" ...
"file002" "file0002" ...
...
"file100" "file0100" ...
...

The pattern is pretty obvious:

name, padded_number

So if I wanted to use string formatting for the files in the first column I would just write

"%s%3d" %[name, number]"

But this hardcodes the padding (3). How can I make it so that I can specify the pad as a variable as well and somehow format the provided integer to use the specified padding?

2 Answers 2

11

Use string interpolation:

padding = 9
"%s%#{padding}d" %[name, number]
Sign up to request clarification or add additional context in comments.

4 Comments

This results in "file" followed by 8 spaces and a "1".
Don't you need a 0 in there? "%s%0#{padding}d"
You guys are right but it still answers his core question, namely embedding a variable in the format string. Yes, his actually format string needs to be tweaked.
format("%s%0#{padding}d", name, number) passes Ruby's style guide validation
9
prefix = "file"
number = "1"
padding = 4
filename = prefix + number.rjust(padding, '0') #=> "file0001"

Comments

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.