Does any feature in Ruby determine the difference between folder levels?

What I'm trying to do is find out if any folders are one of the children / parents or are not related.

Is there any function in the Ruby File API ? if you don’t understand how to understand it?

For instance:

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 

One more 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 # with 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 nil returns:

 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 
+4
source share
2 answers
 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 
+3
source

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 
+3
source

All Articles