Ruby: Extract the hostname from a URL

Updated . Posted . Visible to the public.
url = 'http://www.foocorp.com/foo/bar'
URI.parse(url).host
# => www.foocorp.com

Note that this will raise an error if the given argument is not a URL.

If you need the host's full URL without path, query, fragment etc., use URI.join Show archive.org snapshot with a clever twist:

url = 'http://www.foocorp.com:33546/foo/bar?query=foobar#hash'
URI.join url, '/'
# => http://www.foocorp.com:33546/
Henning Koch
Last edit
Henning Koch
Keywords
host, hostname, domain
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2012-10-25 11:59)