Andrei S
Andrei S

Reputation: 6516

ruby - delete from a string

I have the following strings:

src = "dav://w.lvh.me:3000/Home/Transit/file"
host = "w.lvh.me:3000"

What I want to obtain is "/Home/Transit/file" using those two strings

I thought of searching for host in src and delete it the first time it appears, and everything before it, but I'm not sure exactly how to do that. Or maybe there's a better way?

Any help would be appreciated!

Upvotes: 0

Views: 245

Answers (2)

Victor Deryagin
Victor Deryagin

Reputation: 12225

There is a better way indeed:

require 'uri'
src = "dav://w.lvh.me:3000/Home/Transit/file"
src = URI.parse src

src.path      # => "/Home/Transit/file"

When there are spaces in the string, you must pass extra step of escaping/unescaping. Fortunantly, this is simple:

require 'uri'
src = "dav://w.lvh.me:3000/Home/Transit/Folder 144/webdav_put_request"
src = URI.parse(URL.escape src)

URL.unescape(src.path)      # => "/Home/Transit/Folder 144/webdav_put_request"

Upvotes: 8

Chowlett
Chowlett

Reputation: 46667

This should do the job:

src = "dav://w.lvh.me:3000/Home/Transit/file"
host = "w.lvh.me:3000"
result = src.sub(/.*#{host}/, '')
#=> "/Home/Transit/file"

Upvotes: 2

Related Questions