Insert A Suffix Into A File Name Before The Extension In Ruby

Jul 28, 2014Ryan Burnette

Earlier this evening I had a situation where I needed to insert a suffix into a file name before the extension. I figured I'd need to do this again so I made it a snippet.

There are probably fancier ways to do this using Regex, but all the reversing makes sure that only the last occurence of the extension is used for the insertion.

I can think of some cases where this would break, so I may need to update this to make it more durable.

def suffix_filename(filename, suffix)
  extension = File.extname(filename)
  filename.reverse.sub(extension.reverse, ("#{suffix}#{extension}").reverse).reverse

Fork and Star on Github Gist.

Blog Index