Method: File.common_path

Defined in:
lib/pleasant_path/file.rb

.common_path(paths) ⇒ String

Returns the longest path that all given paths have in common.

Examples:

File.common_path(["a/b/x", "a/b/y", "a/b/z"])  # == "a/b/"
File.common_path(["a/bx", "a/by", "a/bz"])     # == "a/"
File.common_path(["a/b/x", "a/b", "a"])        # == "a"

Parameters:

Returns:



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/pleasant_path/file.rb', line 14

def self.common_path(paths)
  return paths.first if paths.length <= 1
  short, long = paths.minmax
  i = 0
  last = -1
  while i < short.length && short[i] == long[i]
    last = i if short[i] == "/"
    i += 1
  end
  short[0, i == short.length ? i : (last + 1)]
end