How to navigate two directories up ruby

directory, ruby

Solution

There are two ways to do this (well, there are several, but here are two good ones). First, using `File.expand_path`:

original_path = "/repos/something/test-folder/features/support"
target_path = File.expand_path("../../lib/resources", original_path)

p target_path
# => "/repos/something/test-folder/lib/resources"

Note that `File.expand_path` will always return an absolute path, so it's not appropriate if you want to get a relative path back. If you use it, either make sure that the second argument is an absolute path, or, if it's a relative path, that you know what it will expand to (which will depend on the current working directory).

Next, using `Pathname#join` (which is aliased as `Pathname#+`):

require "pathname"

original_path = Pathname("/repos/something/test-folder/features/support")
target_path = original_path + "../../lib/resources"

p target_path
# => #<Pathname:/repos/something/test-folder/lib/resources>

You can also use `Pathname#parent`, but I think it's kind of ugly:

p original_path.parent.parent
# => #<Pathname:/repos/something/test-folder>

p original_path.parent.parent + "lib/resources"
# => #<Pathname:/repos/something/test-folder/lib/resources>

I prefer Pathname because it makes working with paths very easy. In general you can pass the Pathname object to any method that takes a path, but once in awhile a method will balk at anything other than a String, in which case you'll need to cast it as a string first:

p target_path.to_s
# => "/repos/something/test-folder/lib/resources"

P.S. `foo = "#{bar}"` is an antipattern in Ruby. If `bar` is already a String you should just use it directly, i.e. `foo = bar`. If bar isn't already a String (or you're not sure), you should cast it explicitly with `to_s`, i.e. `foo = bar.to_s`.

P.P.S. Global variables are a nasty code smell in Ruby. There is almost always a better way to go than using a global variable.

Problem

In Ruby,I have global variable `$file_folder` that gives me the location of the current config file: ``` $file_folder = "#{File}" $file_folder = /repos/.../test-folder/features/support ``` I need to access a file sitting in a different folder and this folder is two levels up and two levels down. Is there any way to navigate to this target path using the current location? ``` target path = /repos/..../test-folder/lib/resources ```

Original source