40

I'm looking for a method to reliably extract the host name from a URL string in Ruby.

e.g. http://www.mglenn.com/directory = www.mglenn.com OR http://www.mglenn.com?param=x = www.mglenn.com

2 Answers 2

80

You could try something like this:

require 'uri'

myUri = URI.parse( 'http://www.mglenn.com/directory' )
print myUri.host
# =>  www.mglenn.com
Sign up to request clarification or add additional context in comments.

2 Comments

Worth noting - this will fail if the URL is something like example.com (no protocol)
To allow no protocol you can do this: myUri = uri.start_with?('http') ? URI(uri) : URI("http://#{uri}"). Then call myUri.host for the host. Note that this is pretty naiv
28
URI("http://www.mglenn.com/directory").host

1 Comment

Easiest, cleanest solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.