2016-08-28 61 views
-2

好吧,所以我想采取我有的文件路径,删除已知的根路径,并追加一个新的。红宝石 - 替换根路径的新根路径

我会尝试打一个比方:

# 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

你是否试图将文件移动到新的位置,或者只是改变路径的字符串值? – kcdragon

+0

我更新了上面的问题。我正在创建一个文件类型转换器。基本上我有一个路径名,我想改变根目录,这样我就可以在其他地方用转换后的文件重新创建一个目录的结构。 – tedm1106

+0

所以你想复制'root_path'中的所有文件到'new_root'?这比你所描述的要复杂得多。 – kcdragon

回答

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_pathPathname

new_path = original_path.sub(root_path, new_root) 
+0

对不起,我更新了我的问题,所以它不是这么简单。 – tedm1106

+0

谢谢!使用您的解决方案,我能够解决我的大问题。 – tedm1106