私はあなたの質問が正しいことを理解していただきたいと思います。
例:
require 'pathname'
A = '/usr/xxx/a/b/c.txt'
path = Pathname.new(A)
[
'/usr/xxx/a/b',
'/usr/yyy/a/b',
].each{|b|
if path.fnmatch?(File.join(b,'**'))
puts "%s is in %s" % [A,b]
else
puts "%s is not in %s" % [A,b]
end
}
結果:
/usr/xxx/a/b/c.txt is in /usr/xxx/a/b
/usr/xxx/a/b/c.txt is not in /usr/yyy/a/b
ソリューションはclass Pathnameを使用しています。その利点:Pathnameは、ファイルシステム上のファイルまたはディレクトリの名前ですが、ファイル自体は表しません。したがって、ファイルへの読み取りアクセスなしでテストを行うことができます。
テスト自体はPathname#fnmatch?
とglob-pattern File.join(path,'**')
(**
はすべてのサブディレクトリを意味します)で行います。
あなたはより頻繁にそれが必要な場合は、Pathname
を拡張することができます:
require 'pathname'
class Pathname
def is_underneath?(path)
return self.fnmatch?(File.join(path,'**'))
end
end
A = '/usr/xxx/a/b/c.txt'
path = Pathname.new(A)
[
'/usr/xxx/a/b',
'/usr/yyy/a/b',
].each{|b|
if path.is_underneath?(b)
puts "%s is in %s" % [A,b]
else
puts "%s is not in %s" % [A,b]
end
}
絶対/相対pathesを処理するために、それは(申し訳ありませんが、これはテストされていない)のようpathesを拡大するのを助けることができます。
class Pathname
def is_underneath?(path)
return self.expand_path.fnmatch?(File.expand_path(File.join(path,'**')))
end
end