Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby string format formatting

Tags:

ruby

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?

like image 755
MxLDevs Avatar asked Dec 01 '22 22:12

MxLDevs


1 Answers

Use string interpolation:

padding = 9
"%s%#{padding}d" %[name, number]
like image 78
Cody Caughlan Avatar answered Feb 23 '23 16:02

Cody Caughlan