How can I get the filename from a file path in Ruby?
For example if I have a path of \"C:\\projects\\blah.dll\"
and I just want the \"blah\".
Is
In case the extension is not known (it needs the / separator):
irb(main):024:0> f = 'C:\foobar\blah.txt'.gsub("\\","/")
=> "C:/foobar/blah.txt"
irb(main):027:0> File.basename(f,File.extname(f))
=> "blah"
Try this code
Use extname
File.basename("a/b/d/test.rb", File.extname("a/b/d/test.rb")) #=> "test"
Jonathan Lonowski answered perfectly, but there is something that none of the answers mentioned here. Instead of File::extname, you can directly use a '.*'
to get the file name.
File.basename("C:\\projects\\blah.dll", ".*") # => "C:\\projects\\blah"
But, if you want to get the base file name of any specific extension files, then you need to use File::extname
, otherwise not.
Note that double quotes strings escape \'s.
'C:\projects\blah.dll'.split('\\').last
require 'pathname'
Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>
I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.
Try File.basename
Returns the last component of the filename given in file_name, which must be formed using forward slashes (``/’’) regardless of the separator used on the local file system. If suffix is given and present at the end of file_name, it is removed.
File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb" File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
In your case:
File.basename("C:\\projects\\blah.dll", ".dll") #=> "blah"