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
\$\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"
\$\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.

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.