Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

def get_domain
  a = @url.split('.')
  a[-1] =  a[-1].gsub(/\//,'')
  if a[0][-3..-1] == "www"
    a[0] = a[0].gsub(/https?:\/\//,'')
  domain = a.join('.')
rescue => e
  puts e.message
end #end of get_domain
share|improve this question

Use URI::parse:

require 'uri'
URI.parse("").host.sub(/^www\./, '')
#=> ""
share|improve this answer

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\.)?)/, '')

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
Parsing urls by hand is risky, for example try this one: – tokland Feb 27 '13 at 14:26

Your Answer


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.