Remove last segment of an URI in Ruby

只谈情不闲聊 提交于 2019-12-25 00:35:31

问题


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



来源:https://stackoverflow.com/questions/32501082/remove-last-segment-of-an-uri-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!