开发者

Any Function in Ruby determine the difference between folders level?

开发者 https://www.devze.com 2023-01-29 00:49 出处:网络
What I\'m trying to do is to figure out if some folders is one of children / parents Or not related. Is there any function in the Ruby File API? if not how to figure it out?

What I'm trying to do is to figure out if some folders is one of children / parents Or not related.

Is there any function in the Ruby File API? if not how to figure it out?

For example:

real_path_1 = "/Users/amr/Code/xx/zz"
real_path_2 = "/Users/amr/Code/"
# when I have to compare between these paths like:
f_level(real_path_1, real_path_2)
# it should return +2
# that means real_path_1 is **parent** of real_path_2
# with 2 levels depth

Also another example:

real_path_1 = "/Users/amr/Code/"
real_path_2 = "/Users/amr/Code/foo/bar/inside"
# when I have to compare between these paths like:
f_level(real_path_1, real_path_2)
# it should return -3
# that means real_path_1 is **child** of real_path_2
# w开发者_JS百科ith 3 levels depth

Another example:

real_path_1 = "/Users/amr/Code/"
real_path_2 = "/Users/amr/Code/"
# when I have to compare between these paths like:
f_level(real_path_1, real_path_2)
# it should return 0
# that means real_path_1 is **same level** as real_path_2

When returns nil:

real_path_1 = "/Users/other/Code/" # or "/folder2/"
real_path_2 = "/Users/amr/Code/" # or "/folder1/"
# when I have to compare between these paths like:
f_level(real_path_1, real_path_2)
# it should return nil
# that means real_path_1 is **not at same level** as real_path_2


def f_level a,b
    if a[/^#{b}/] && (b[-1,1] == '/' || $'[0,1] == '/')
        $'.scan(/[^\/]+/).size
    elsif b[/^#{a}/] && (a[-1,1] == '/' || $'[0,1] == '/')
        -($'.scan(/[^\/]+/).size)
    end
end

"/Users/amr/Code/xx/zz"
"/Users/amr/Code/"
2
"/Users/amr/Code/"
"/Users/amr/Code/xx/zz"
-2
"/Users/amr/Code/"
"/Users/amr/Code/"
0
"/Users/other/Code/"
"/Users/amr/Code/"
nil


Another idea without regular expressions:

def f_level(path1_string, path2_string)
  path1, path2 = [path1_string, path2_string].map { |s| s.split(File::SEPARATOR) }  
  minsize = [path1, path2].map(&:size).min
  path1.first(minsize) == path2.first(minsize) ? path1.size - path2.size : nil
end

raise unless f_level("/Users/amr/Code/xx/zz",  "/Users/amr/Code/") == 2
raise unless f_level( "/Users/amr/Code/", "/Users/amr/Code/foo/bar/inside") == -3
raise unless f_level("/Users/amr/Code/", "/Users/amr/Code/") == 0 
raise unless f_level("/Users/other/Code/", "/Users/amr/Code/") == nil
0

精彩评论

暂无评论...
验证码 换一张
取 消