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)
mu *_*ort 11
使用URI.parse然后将其设置path为空字符串,然后设置query为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
Run Code Online (Sandbox Code Playgroud)
现在你已经清理了版本cleaned.取出你不想要的东西有时比仅仅抓住你需要的东西更容易.
如果你这样做,uri.query = ''你最终http://foo.example.com:8080?可能不是你想要的.
| 归档时间: |
|
| 查看次数: |
5970 次 |
| 最近记录: |