1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数のパスの共通のプリフィクスを求める(2)

Posted at

下のようなメソッドで、複数のパスの共通のプリフィクスを取得できます。

  • 意図しないところでDir.chdirするかも知れないので(他のスレッドとか)パスは全部フルパスにしておきたい
  • でもユーザーへの表示とかどこかへの出力には極力短いパス名を使いたい

という時に使えます。

require 'pathname'
require 'pathname/common_prefix'

paths = %w[
  /path/to/base/dir/and/file1
  /path/to/base/dir/and/file2
  /path/to/base/dir/and/subdir/file1
  /path/to/base/dir/and/sub/dir/file2
].map {|path| Pathname(path)}
dir = Pathname.common_prefix(*paths) # => #<Pathname:/path/to/base/dir/and>
puts paths.map {|path| path.relative_path_from(dir)}
# file1
# file2
# subdir/file1
# sub/dir/file2

……のですが、こんな需要あるのかな?
僕は必要なので書いたんですけど。
以下がメソッドの実装です。

require 'pathname'

class Pathname
  class << self
    def common_prefix(*paths)
      base = paths.pop
      return if base.nil?
      base.common_prefix(*paths)
    end
  end

  def common_prefix(*paths)
    paths = paths.map {|path| path.enum_for(:descend)}
    last_filename = nil
    enum_for(:descend).each do |filename|
      break unless paths.all? {|path|
        begin
          filename == path.next
        rescue StopIteration
        end
      }
      last_filename = filename
    end
    last_filename
  end
end
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?