Filename without extension in Ruby

posted 2012-Mar-23

Ruby’s File.basename method gives you the name of a file in a path string:

File.basename( "foo/bar/jim-jam/whee.html" )       #=> "whee.html"

Not clearly explained in the documentation, however, is the fact you can pass a second parameter of ".*" to remove any extension from that file:

File.basename( "foo/bar/jim-jam/whee.html", ".*" ) #=> "whee"

Want a path to the same file with a different extension (e.g. changing a “.png” to a “.jpg”)? You could do this:

filename  = File.basename(my_path,".*")
othername = File.join( File.dirname(my_path), "#{filename}.jpg" )

…but I’d rather just do this:

# replace non-period characters after a period, at the end of the string, with '.jpg'
othername = my_path.sub /\.[^.]+\z/, ".jpg"  
Pavel K
09:57AM ET
2013-Dec-12

ideally: othername = my_path.sub(/.[^.]+\z/,”.jpg”) # replace non-period characters at the end of the string with ‘jpg’

not all files have extensions

Gavin Kistner
11:31AM ET
2015-May-17

@PavelK: Excellent point. I’ve modified the code to match.

net.mind details contact résumé other
Phrogz.net