Remove last segment of an URI in Ruby

2019-09-01 10:44发布

问题:

I'm trying to remove the last segment of a given URI using Ruby,

like this:

http://example.com/foo/bar/baz/?lala=foo

How can I get this :

"http://example.com/foo/bar/baz/"

I've searched and all that I got is to get the last segment or the host part of the URI.

回答1:

Based on your comment to @JorgWMittag all your really need is this

s = 'http://example.com/foo/bar/baz/?lala=foo#quux'
s[/.*\//]
#=> "http://example.com/foo/bar/baz/"
s = 'http://example.com/foo/bar.html'
s[/.*\//]
#=> "http://example.com/foo/"

Basically it just says grab the substring up to the last slash obviously if you have things like

s = "http://example.com/foo/bar/?baz=/blah/blah"

Then this will not work but your question and specifications seem very loose at the moment.



回答2:

The most important thing to remember is: Ruby is an object-oriented language. It's not an array-oriented language, it's not a hash-oriented language, it's not a string-oriented language.

When you want to do something, you construct an object which represents your concept and manipulate that object. In this case, you want to manipulate a URI, so you need to construct an object which represents a URI.

Thankfully, the Ruby standard library already contains a ready-made class for such objects:

require 'uri'

uri = URI.parse('http://example.com/foo/bar/baz/?lala=foo#quux')

uri.query = nil

uri
# => #<URI::HTTP http://example.com/foo/bar/baz/#quux>

uri.to_s
# => 'http://example.com/foo/bar/baz/#quux'

uri.fragment = nil

uri
# => #<URI::HTTP http://example.com/foo/bar/baz/>

uri.to_s
# => 'http://example.com/foo/bar/baz/'

As you can see, once you create a proper object representing your URI, manipulating it becomes trivial.



回答3:

s = "http://example.com/foo/bar/baz/?lala=foo"
"http://example.com/foo/bar/baz/?lala=foo"
["http://example.com/foo/bar/baz/", "lala=foo"]
>> s.split("?").first
"http://example.com/foo/bar/baz/"

Did you tried something like this, possibly the first thing when you want to split a string



标签: ruby uri