How to navigate two directories up the ruby

In Ruby, I have a global variable $file_folderthat gives me the location of the current configuration file:

$file_folder = "#{File}"
$file_folder = /repos/.../test-folder/features/support

I need to access a file sitting in another folder, and this folder is two levels up and two levels down. Is there a way to navigate to this destination path using the current location?

target path = /repos/..../test-folder/lib/resources
+4
source share
1 answer

There are two ways to do this (well, there are several, but there 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"

, File.expand_path , , . , , , , , , ( ).

, Pathname#join ( 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>

Pathname#parent, :

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

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

Pathname, . Pathname , , - , String, :

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

P.S. foo = "#{bar}" Ruby. bar , , .. foo = bar. bar ( ), to_s, .. foo = bar.to_s.

P.P.S. - Ruby. , .

+3

Source: https://habr.com/ru/post/1547448/


All Articles