Refactor Ruby method for getting domain?

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

-

Use URI::parse:

require 'uri'
URI.parse("http://gist.github.com/a/b/c").host.sub(/^www\./, '')
#=> "gist.github.com"

-

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.

-
Parsing urls by hand is risky, for example try this one: http://user:password@server.org/path/file. –  tokland Feb 27 '13 at 14:26