2016-10-22 49 views
1

说我有这样的URL:http://www.rubinassociatespa.com/AccountantBocaRaton.html如何在Ruby中使用URI类从域中提取根域?

我只想提取基本域 - http://www.rubinassociatespa.com

我无法弄清楚如何使用Ruby URI类,但是没有做的字符串操作来做到这一点。

[36] pry(#<YPCrawler::PageParser>)> @url 
=> "http://www.rubinassociatespa.com/AccountantBocaRaton.html" 
[37] pry(#<YPCrawler::PageParser>)> URI(@url).scheme 
=> "http" 
[38] pry(#<YPCrawler::PageParser>)> URI(@url).host 
=> "www.rubinassociatespa.com" 

要使用字符串操作做到这一点,我将不得不做这样的事情:

URI(@url).scheme + "://" + URI(@url).host 

但似乎哈克。

是否有更“原生”的方式来做到这一点?一些很酷的方法或类似URI类可以优雅地处理这个?

+0

有没有开箱即用的方法。 – Ilya

回答

1

我总是用:

▶ uri.to_s[/\A.*(?=#{uri.path}\z)/] 
#⇒ "http://www.rubinassociatespa.com" 

这是安全的,因为它正是基域是什么:整个URI不带路径。

请注意,由于URI类extensibility和RFC本身的灵活性,不会有任何统一的方法。