How to get filename without extension from file path in Ruby

前端 未结 9 1171
感情败类
感情败类 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:42

    Jonathon's answer is better, but to let you know somelist[-1] is one of the LastIndexOf notations available.

    As krusty.ar mentioned somelist.last apparently is too.

    irb(main):003:0* f = 'C:\\path\\file.txt'
    irb(main):007:0> f.split('\\')
    => ["C:", "path", "file.txt"]
    irb(main):008:0> f.split('\\')[-1]
    => "file.txt"
    
    0 讨论(0)
  • 2020-11-29 17:46

    If you have access to ENV variables, scan combined with this little regex (which finds the last but one word, a dot, then the last word of the string) will put the file's name into 'filename':

    filename = ENV['SCRIPT_NAME'].scan(/\w+\.\w+$/)
    

    Obviously, you can use scan and the regex on any path name that includes the filename, and __FILE__ is the obvious choice:

    __FILE__.scan(/\w+\.\w+$/)
    
    0 讨论(0)
  • 2020-11-29 17:49

    You can get directory path to current script with:

    File.dirname __FILE__
    
    0 讨论(0)
提交回复
热议问题