MxLDevs
MxLDevs

Reputation: 19546

ruby string format formatting

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?

Upvotes: 6

Views: 8116

Answers (2)

steenslag
steenslag

Reputation: 80085

prefix = "file"
number = "1"
padding = 4
filename = prefix + number.rjust(padding, '0') #=> "file0001"

Upvotes: 9

Cody Caughlan
Cody Caughlan

Reputation: 32748

Use string interpolation:

padding = 9
"%s%#{padding}d" %[name, number]

Upvotes: 11

Related Questions