tedm1106 tedm1106 - 3 months ago 10
Ruby Question

Ruby - Substitute root of path for new root path

Okay, so I want to take a file path that I have, remove a known root path, and append a new one.

I will attempt to make an example:

# 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/'


So, I have
original_path
, which is a path object. And I want to remove
root_path
from this, and apply
new_root
to the front of it. How can I do this?

EDIT:

This is my real problem, sorry for the poor explaination before:

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/'


Now how do you substitute those?

Answer

If you are just trying to get a new string, you can do this

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

Edit

You can still use sub instead of gsub if original_path is a Pathname

new_path = original_path.sub(root_path, new_root)