在 Ruby 中查找文件名的扩展名

我正在做一个 Rails 应用程序的文件上传部分。不同类型的文件由应用程序进行不同的处理。

我想做一个白名单的某些文件扩展名检查上传的文件,看看他们应该去哪里。所有的文件名都是字符串。

我需要一种只检查文件名字符串扩展部分的方法。文件名都是“ some _ file _ name”格式。某种延伸”。

104834 次浏览

使用 File 类中的 extname方法

File.extname("test.rb")         #=> ".rb"

你也可能需要 basename方法

File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"
irb(main):002:0> accepted_formats = [".txt", ".pdf"]
=> [".txt", ".pdf"]
irb(main):003:0> File.extname("example.pdf") # get the extension
=> ".pdf"
irb(main):004:0> accepted_formats.include? File.extname("example.pdf")
=> true
irb(main):005:0> accepted_formats.include? File.extname("example.txt")
=> true
irb(main):006:0> accepted_formats.include? File.extname("example.png")
=> false

这是一个很老的话题,但是下面是去掉扩展分隔符点和可能的尾随空格的方法:

File.extname(path).strip.downcase[1..-1]

Examples:

File.extname(".test").strip.downcase[1..-1]       # => nil
File.extname(".test.").strip.downcase[1..-1]      # => nil
File.extname(".test.pdf").strip.downcase[1..-1]   # => "pdf"
File.extname(".test.pdf ").strip.downcase[1..-1]  # => "pdf"

我个人认为,这样做会更容易摆脱扩展分隔符。

File.extname(path).delete('.')

这篇文章回答了我的问题,但是我的用例正好相反。我想找到没有扩展名的文件名。我用 File.basename找到了文件名,然后将 File.extnamegsub组合起来,像这样移除了 .md:

@file = '/path/to/my-file-name.md'
File.basename(@file).gsub(File.extname(@file),'')


# => 'my-file-name'