您将如何解析Ruby中的url来获取主域? [英] How would you parse a url in Ruby to get the main domain?
本文介绍了您将如何解析Ruby中的url来获取主域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想能够使用红宝石解析任何url来获取域的主要部分,而没有 www
(只是XXXX.com)
I want to be able to parse any url with ruby to get the main part of the domain without the www
(just the XXXX.com)
推荐答案
这应该适用于几乎任何URL:
This should work with pretty much any URL:
# URL always gets parsed twice
def get_host_without_www(url)
url = "http://#{url}" if URI.parse(url).scheme.nil?
host = URI.parse(url).host.downcase
host.start_with?('www.') ? host[4..-1] : host
end
或:
# Only parses twice if url doesn't start with a scheme
def get_host_without_www(url)
uri = URI.parse(url)
uri = URI.parse("http://#{url}") if uri.scheme.nil?
host = uri.host.downcase
host.start_with?('www.') ? host[4..-1] : host
end
您可能需要code> require'uri'。
You may have to require 'uri'
.
这篇关于您将如何解析Ruby中的url来获取主域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文