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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8082444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:19:59  来源:igfitidea点击:

Find the extension of a filename in Ruby

ruby-on-railsruby

提问by Bryan Cosgrove

I'm working on the file upload portion of a Rails app. Different types of files are handled differently by the app.

我正在处理 Rails 应用程序的文件上传部分。应用程序以不同方式处理不同类型的文件。

I want to make a whitelist of certain file extensions to check the uploaded files against to see where they should go. All of the file names are strings.

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

I need a way to check only the extension part of the file name string. The file names are all in the format of "some_file_name.some_extension".

我需要一种方法来只检查文件名字符串的扩展名部分。文件名都是“some_file_name.some_extension”格式。

回答by Felix

That's really basic stuff:

这真的是基本的东西:

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

回答by megas

Use extnamemethod from File class

使用extnameFile 类中的方法

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

Also you may need basenamemethod

你也可能需要basename方法

File.basename("/home/gumby/work/ruby.rb", ".rb")   #=> "ruby"

回答by gertas

Quite old topic but here is the way to get rid of extension separator dot and possible trailing spaces:

很老的话题,但这里是摆脱扩展分隔符点和可能的尾随空格的方法:

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"