Ruby / Rails 3.1:给定一个URL字符串,删除路径

给定任何有效的HTTP / HTTPS字符串,我想解析/转换它,使得最终结果正好是字符串的根。

给定的URL:

http://foo.example.com:8080/whatsit/foo.bar?x=y https://example.net/ 

我想结果:

 http://foo.example.com:8080/ https://example.net/ 

我发现URI :: Parser的文档不是非常平易近人的。

我最初的,天真的解决方案是一个简单的正则表达式:

 /\A(https?:\/\/[^\/]+\/)/ 

(即:匹配协议后的第一个斜杠。)

欢迎思考和解决方案。 如果这是重复的,请道歉,但我的搜索结果不相关。

使用URI :: join :

 require 'uri' url = "http://foo.example.com:8080/whatsit/foo.bar?x=y" baseurl = URI.join(url, "/").to_s #=> "http://foo.example.com:8080/" 

使用URI.parse ,然后将path设置为空字符串,并将querynil

 require 'uri' uri = URI.parse('http://foo.example.com:8080/whatsit/foo.bar?x=y') uri.path = '' uri.query = nil cleaned = uri.to_s # http://foo.example.com:8080 

现在您已将清理后的版本cleaned 。 取出你不想要的东西有时比仅仅抓住你需要的东西更容易。

如果你只做uri.query = ''你最终会得到http://foo.example.com:8080? 这可能不是你想要的。

您可以使用uri.split()然后将这些部件放回原处……

警告:这有点草率。

 url = "http://example.com:9001/over-nine-thousand" parts = uri.split(url) puts "%s://%s:%s" % [parts[0], parts[2], parts[3]] => "http://example.com:9001"