【问题标题】:Ruby - Substitute root of path for new root pathRuby - 用路径的根替换新的根路径
【发布时间】:2017-01-04 19:49:27
【问题描述】:

好的,所以我想采用我拥有的文件路径,删除一个已知的根路径,然后追加一个新路径。

我会尝试做一个例子:

# This one is a path object
original_path = '/home/foo/bar/path/to/file.txt'
# This one is a string
root_path = '/home/foo/bar/'
# This is also a string
new_root = '/home/new/root/'

所以,我有original_path,它是一个路径对象。我想从中删除root_path,并将new_root 应用到它的前面。我该怎么做?

编辑:

这是我真正的问题,抱歉之前的解释不好:

require 'pathname'

# This one is a path object
original_path = Pathname.new('/home/foo/bar/path/to/file.txt')
# This one is a string
root_path = '/home/foo/bar/'
# This is also a string
new_root = '/home/new/root/'

现在你如何替换那些?

【问题讨论】:

  • 您是想将文件移动到新位置还是只是更改路径的字符串值?
  • 我在上面更新了我的问题。我正在创建一个文件类型转换器。基本上我有一个路径名,我想更改根目录,这样我就可以在其他地方“重新创建”目录结构,其中包含转换后的文件。
  • 所以你想将root_path中的所有文件复制到new_root?这比你描述的要复杂得多。
  • 不一定要直接复制,而是先通过函数运行,再用新的扩展名吐出来。

标签: ruby string file path


【解决方案1】:

如果你只是想获得一个新的字符串,你可以这样做

# This one is a path object
original_path = '/home/foo/bar/path/to/file.txt'
# This one is a string
root_path = '/home/foo/bar/'
# This is also a string
new_root = '/home/new/root/'

new_path = original_path.gsub(root_path, new_root)

编辑

如果original_pathPathname,您仍然可以使用sub 而不是gsub

new_path = original_path.sub(root_path, new_root)

【讨论】:

  • 对不起,我更新了我上面的问题,所以没有这么简单。
  • 谢谢!使用您的解决方案,我能够解决更大的问题。
猜你喜欢
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 2016-12-23
  • 2013-12-29
  • 2011-08-14
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多