好的,所以我想获取我拥有的文件路径,删除已知的根路径,然后添加一个新路径。
我将尝试举例:
# 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/'
现在你如何替代那些?
答案 0 :(得分: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)
修改
如果sub
是gsub
original_path
代替Pathname
new_path = original_path.sub(root_path, new_root)