Ruby/Rails 3.1:给定一个 URL 字符串,删除路径 [英] Ruby/Rails 3.1: Given a URL string, remove path

查看:42
本文介绍了Ruby/Rails 3.1:给定一个 URL 字符串,删除路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given any valid HTTP/HTTPS string, I would like to parse/transform it such that the end result is exactly the root of the string.

给定的网址:

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

我想要结果:

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

我找到了文档对于 URI::Parser 不是超级平易近人.

I found the documentation for URI::Parser not super approachable.

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

My initial, naïve solution would be a simple regex like:

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

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

(That is: Match up to the first slash after the protocol.)

想法和想法欢迎解决.如果这是重复的,我很抱歉,但我的搜索结果不相关.

Thoughts & solutions welcome. And apologies if this is a duplicate, but my search results weren't relevant.

推荐答案

With 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/"

这篇关于Ruby/Rails 3.1:给定一个 URL 字符串,删除路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆