1

我正在尝试将目录中的文件与其他目录中的其他文件以及使用 ruby​​ 的子目录进行匹配。

我尝试使用此文件体系结构进行小测试:

tree .
.
├── src
│   ├── lol
│   │   └── toto
│   └── lolilolpouet
│       └── tutu
│           └── tata
├── test
│   ├── tata
│   └── toto
└── test.rb

我的红宝石代码是:

require 'find'

src_dir_files = []
Find.find('./src') do |file|
  src_dir_files << file
  puts "found #{file}"
end


Dir.foreach('./test') do |file|
  next if file == '.' or file == '..'
  puts "search for /#{file}"
  res = src_dir_files.bsearch{|s| s.end_with? "/#{file}"}
  puts "Found :#{res}"
end

输出是:

found ./src
found ./src/lol
found ./src/lol/toto
found ./src/lolilolpouet
found ./src/lolilolpouet/tutu
found ./src/lolilolpouet/tutu/tata
search for /tata
Found :./src/lolilolpouet/tutu/tata
search for /toto
Found :

搜索 toto 不会返回任何结果。知道为什么,以及如何解决吗?

编辑:如果我用 find 替换 bsearch,上面的代码将按预期运行。谁能向我解释这两种方法之间的区别?

如果你想试试,我上传了一个 tgz:

http://cl.ly/331J0C2e2D0Y

4

2 回答 2

1

我会做如下:

src = Dir["./src/**/*"] 
#=> ["./src/lol", "./src/lol/toto", "./src/lolilolpouet", "./src/lolilolpouet/tutu", "./src/lolilolpouet/tutu/tata"]
Dir["./test/**/*"].each do |test_file|
  file = src.find { |x| x.include? test_file.gsub(/.*\//, "") }
  puts "Found #{file}"
end

# >> Found ./src/lolilolpouet/tutu/tata
# >> Found ./src/lol/toto
于 2014-02-26T01:33:10.770 回答
0

我猜这src_dir_files不是排序的。

于 2014-02-26T02:34:53.957 回答