删除“。”和“..”在目录中工作

时间:2011-08-24 11:49:40

标签: ruby-on-rails ruby ruby-on-rails-3

我想编写一个从用户获取路径的程序,然后再次转到该目录和所有子目录并收集所有txt文件。但是“。”和“..”当我重复迭代目录时打扰我。请帮我消除这个问题。 这是我的代码:

def detect_files(path)
            Dir.foreach(path) do |i|
        if (i != "." or i !="..")
            if (File.directory?(i))
                detect_files(i)
            end
            if (i.reverse.start_with?("txt."))
                @files[i]=[]
            end
        end
    end

end

5 个答案:

答案 0 :(得分:4)

条件应该是:

if (i != "." and i != "..")
  • 如果i=".",则i != "."将为假,条件为false,"."将不会被处理
  • 如果i=".."i != "."为真,但i != ".."为假,则条件为false,".."将不会被处理。
  • 如果i有任何其他值,则and的两边都将为true,if的正文将被执行。

答案 1 :(得分:1)

Dir.foreach(path) do |i|
  next if %w(. ..).include?(i)
  # rest of your code
end

您当前版本的if条件错误:您想要(i != '.' AND i != '..')

答案 2 :(得分:1)

all_txt_files = Dir['**/*.txt']

答案 3 :(得分:0)

你可以尝试做这样的事情

def detect_files(path)
  p1 = File.join(path, '**', '*.txt')
  @files = Dir[p1]
 end

答案 4 :(得分:0)

试试这样:

Dir.foreach('/path/to/dir') do |item|
  next if item == '.' or item == '..'
  # do work on real items
end

OR

Dir.glob('/path/to/dir/*.rb') do |rb_file|
  # do work on files ending in .rb in the desired directory
end