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

Ruby on rails Ruby/Rails 3.1:给定URL字符串,删除路径,ruby-on-rails,ruby,ruby-on-rails-3.1,Ruby On Rails,Ruby,Ruby On Rails 3.1,给定任何有效的HTTP/HTTPS字符串,我希望对其进行解析/转换,以便最终结果正好是字符串的根 因此,给定URL: http://foo.example.com:8080/whatsit/foo.bar?x=y https://example.net/ 我想知道结果: http://foo.example.com:8080/ https://example.net/ 我发现for URI::解析器不是超级可接近的 我最初的天真解决方案是一个简单的正则表达式,如: /\A(https?:\/

给定任何有效的HTTP/HTTPS字符串,我希望对其进行解析/转换,以便最终结果正好是字符串的根

因此,给定URL:

http://foo.example.com:8080/whatsit/foo.bar?x=y
https://example.net/
我想知道结果:

http://foo.example.com:8080/
https://example.net/
我发现for URI::解析器不是超级可接近的

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

/\A(https?:\/\/[^\/]+\/)/
(即:匹配协议后的第一个斜杠。)


欢迎提出想法和解决方案。如果这是重复的,请道歉,但我的搜索结果与此无关。

您可以使用
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"
使用并将
路径设置为空字符串,将
查询设置为
nil

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
现在,您在
已清理的
中有了已清理的版本。拿出你不想要的东西有时比只拿你需要的东西容易

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

使用:


嗯,好吧,我也可以包括港口。URL中也可能有userinfo。是的,我知道,我对病理病例很挑剔:)并检查
URI#split
是否有其他类型的信息你可能想清除(或不清除),例如userinfo,fragment,…以免有人试图使用我上面天真的“解决方案”-请注意它无法匹配没有路径时省略尾部斜杠的URL,也就是说,
http://example.com
而不是
http://example.com/
。我非常喜欢这个答案。事后看来,这是显而易见的<代码>URI。加入是最好的!非常感谢。
require 'uri'
url = "http://foo.example.com:8080/whatsit/foo.bar?x=y"
baseurl = URI.join(url, "/").to_s
#=> "http://foo.example.com:8080/"