HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Refactor Ruby method for getting domain?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodgettingforrubyrefactordomain

Problem

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

Solution

Use URI::parse:

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

Code Snippets

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

Context

StackExchange Code Review Q#23205, answer score: 6

Revisions (0)

No revisions yet.