gpt4 book ai didi

ruby - 将绝对路径与 Pathname 类连接起来

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:04 25 4
gpt4 key购买 nike

我正在做一个项目,我有一个动态确定的挂载点,并提供了一组绝对路径来处理目标卷。由于这些文件尚不存在,我使用 Pathname 类来处理文件名操作。但是,在连接具有相同根的路径时,Pathname 似乎做得有点聪明。我观察到以下行为:

p1 = Pathname.new('/foo/bar')                         # #<Pathname:/foo/bar>
p2 = Pathname.new('/baz/quux') # #<Pathname:/baz/quux>
p3 = p1 + p2 # #<Pathname:/baz/quux>
p4 = p1.join p2.relative_path_from(Pathname.new('/')) # #<Pathname:/foo/bar/baz/quux>
p5 = Pathname.new(p1.to_s.concat p2) # #<Pathname:/foo/bar/baz/quux>

因此,对于 p4 和 p5,我可以获得我想要的行为,但结构有点做作。有没有更简洁的方法来做到这一点?

最佳答案

这里使用字符串操作来解决 Ruby 的奇怪行为相当容易。

借用OP的例子...

p1 = Pathname.new('/foo/bar')
p2 = '/baz/quux'
p1 + p2.sub(/\A\//, '')
# => #<Pathname:/foo/bar/baz/quux>

警告:第二个p2 必须是String 才能发生sub 操作。您可以使用 #to_s 轻松转换 Pathname 对象。

Pathname.new('/some/path/').to_s
# => "/some/path"

关于ruby - 将绝对路径与 Pathname 类连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com