加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在ruby中导航两个目录

发布时间:2020-12-17 02:22:49 所属栏目:百科 来源:网络整理
导读:在 Ruby中,我有全局变量$file_folder,它为我提供了当前配置文件的位置: $file_folder = "#{File}"$file_folder = /repos/.../test-folder/features/support 我需要访问一个位于不同文件夹中的文件,这个文件夹分为两级,两级.有没有办法使用当前位置导航到此
在 Ruby中,我有全局变量$file_folder,它为我提供了当前配置文件的位置:

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

我需要访问一个位于不同文件夹中的文件,这个文件夹分为两级,两级.有没有办法使用当前位置导航到此目标路径?

target path = /repos/..../test-folder/lib/resources

解决方法

有两种方法可以做到这一点(好吧,有几种,但这里有两个好的方法).首先,使用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"

附: foo =“#{bar}”是Ruby中的反模式.如果bar已经是String,你应该直接使用它,即foo = bar.如果bar不是String(或者您不确定),则应使用to_s显式转换它,即foo = bar.to_s.

P.P.S.全局变量在Ruby中是令人讨厌的代码味道.几乎总有一种比使用全局变量更好的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读