Remove last segment of an URI in Ruby

2019-09-01 10:42发布

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.

标签: ruby uri
3条回答
2楼-- · 2019-09-01 10:57

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.

查看更多
甜甜的少女心
3楼-- · 2019-09-01 10:57
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

查看更多
爷的心禁止访问
4楼-- · 2019-09-01 11:15

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.

查看更多
登录 后发表回答