4
\$\begingroup\$

How do I make this more Ruby like? I want to return the host, for example if the URL is "http://www.facebook.com" then I want to get 'facebook.com'.

Any other sub-domains without 'www' should give the subdomin as well. If the URL is "http://gist.github.com" then I want 'gist.github.com':

def get_domain
 a = @url.split('.')
 a[-1] = a[-1].gsub(/\//,'')
 if a[0][-3..-1] == "www"
 a.delete_at(0)
 else
 a[0] = a[0].gsub(/https?:\/\//,'')
 end
 domain = a.join('.')
 domain
rescue => e
 puts e.message
end #end of get_domain
asked Feb 27, 2013 at 6:35
\$\endgroup\$
0

2 Answers 2

6
\$\begingroup\$

Use URI::parse:

require 'uri'
URI.parse("http://gist.github.com/a/b/c").host.sub(/^www\./, '')
#=> "gist.github.com"
answered Feb 27, 2013 at 14:25
\$\endgroup\$
1
\$\begingroup\$

This is looking like a custom requirement. By looking at your code, you want to remove http(s) and www. part of the url

def get_custom_domain
 @url.gsub(/^((https?:\/\/)?(www\.)?)/, '')
end

But it will be better if you give more example of what you exactly want. I have written some specs here Please update it if i am missing some edge case.

answered Feb 27, 2013 at 7:19
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Parsing urls by hand is risky, for example try this one: http://user:[email protected]/path/file. \$\endgroup\$ Commented Feb 27, 2013 at 14:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.