2016-08-28 3 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을 적용하고 싶습니다. 어떻게해야합니까?

편집 :

이 내 진짜 문제는, 전에 가난한 explaination 미안됩니다 : 이제

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

경우, 당신은 당신은 여전히 ​​sub 대신 gsub을 사용할 수 있습니다

# 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) 

편집 할 수 있습니다 파일을 새 위치로 이동 시키거나 경로의 문자열 값을 변경하려고합니까? – kcdragon

+0

위 문제를 업데이트했습니다. 파일 형식 변환기를 만드는 중입니다. 기본적으로 나는 경로명을 가지고 있으며 변환 된 파일을 가진 다른 곳의 디렉토리 구조를 '다시 만들 수 있도록'루트 디렉토리를 변경하려고합니다. – tedm1106

+0

그래서'root_path'에있는 모든 파일을'new_root'에 복사하고 싶습니까? 이것은 당신이 묘사하고있는 것보다 훨씬 더 복잡합니다. – kcdragon

답변

1

당신은 단지 새로운 문자열을 얻으려고 노력하는 경우 original_pathPathname

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

죄송합니다, 위의 내 문제를 업데이트하므로 간단하지 않습니다. – tedm1106

+0

고마워요! 귀하의 솔루션을 사용하여 큰 문제를 해결할 수있었습니다. – tedm1106

관련 문제