How to get filename without extension from file path in Ruby

前端 未结 9 1170
感情败类
感情败类 2020-11-29 17:04

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

相关标签:
9条回答
  • 2020-11-29 17:23

    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"
    
    0 讨论(0)
  • 2020-11-29 17:26

    Try this code

    Use extname

     File.basename("a/b/d/test.rb", File.extname("a/b/d/test.rb")) #=> "test" 
    
    0 讨论(0)
  • 2020-11-29 17:27

    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.

    0 讨论(0)
  • 2020-11-29 17:28

    Note that double quotes strings escape \'s.

    'C:\projects\blah.dll'.split('\\').last
    
    0 讨论(0)
  • 2020-11-29 17:31
    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.

    0 讨论(0)
  • 2020-11-29 17:32

    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"
    
    0 讨论(0)
提交回复
热议问题