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

Ala*_* H. 10 ruby ruby-on-rails ruby-on-rails-3.1

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

给定的URL:

http://foo.example.com:8080/whatsit/foo.bar?x=y
https://example.net/
Run Code Online (Sandbox Code Playgroud)

我想结果:

http://foo.example.com:8080/
https://example.net/
Run Code Online (Sandbox Code Playgroud)

我发现URI :: Parser 的文档不是很平易近人.

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

/\A(https?:\/\/[^\/]+\/)/
Run Code Online (Sandbox Code Playgroud)

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

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

tok*_*and 27

使用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/"
Run Code Online (Sandbox Code Playgroud)

  • 我真的很喜欢这个答案.事后看来很明显.`URI.join`是最好的!谢谢! (2认同)

mu *_*ort 11

使用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
Run Code Online (Sandbox Code Playgroud)

现在你已经清理了版本cleaned.取出你不想要的东西有时比仅仅抓住你需要的东西更容易.

如果你这样做,uri.query = ''你最终http://foo.example.com:8080?可能不是你想要的.

  • 并检查`URI#split`以获取您可能想要清除(或不清除)的其他类型的信息,例如userinfo,fragment,... (2认同)