Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question
add comment

2 Answers 2

Use URI::parse:

require 'uri'
URI.parse("http://gist.github.com/a/b/c").host.sub(/^www\./, '')
#=> "gist.github.com"
share|improve this answer
add comment

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.

share|improve this answer
1  
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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