有没有办法在Linux下的Ruby中不区分大小写地打开文件?例如,给定字符串foo.txt
,我可以打开该文件吗FOO.txt
?
一种可能的方法是读取目录中的所有文件名并手动搜索所需文件的列表,但我正在寻找一种更直接的方法。
一种方法是编写一个小方法来为给定的文件名构建不区分大小写的 glob:
def ci_glob(filename)
glob = ''
filename.each_char do |c|
glob += c.downcase != c.upcase ? "[#{c.downcase}#{c.upcase}]" : c
end
glob
end
irb(main):024:0> ci_glob('foo.txt')
=> "[fF][oO][oO].[tT][xX][tT]"
然后你可以这样做:
filename = Dir.glob(ci_glob('foo.txt')).first
或者,您可以非常简洁地编写您建议的目录搜索。例如
filename = Dir.glob('*').find { |f| f.downcase == 'foo.txt' }
在 Ruby 3.1 之前,可以使用FNM_CASEFOLD
选项使glob
不区分大小写,例如
filename = Dir.glob('foo.txt', File::FNM_CASEFOLD).first
if filename
# use filename here
else
# no matching file
end
文档建议FNM_CASEFOLD不能与 glob 一起使用 http://ruby-doc.org/core-2.2.2/Dir.html#method-c-glob but it did实际上可以在旧的 Ruby 版本中工作。然而,正如所提到的lildude https://stackoverflow.com/users/573122/lildude in the comments https://stackoverflow.com/questions/3651952/open-a-file-case-insensitively-in-ruby-under-linux/3652293?noredirect=1#comment131378420_3652293, the 行为现已内联 https://github.com/ruby/ruby/pull/4583与文档,所以不应该使用这种方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)