Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse URL in Ruby to get subdomain or main domain without "www"?

Tags:

ruby

If I had an URL:

http://www.example.com/page

I would like to interpret that to:

example.com

But, if I had:

http://blog.example.com/page

I'd like to get back:

blog.example.com

Is that difficult?

like image 937
Alfo Avatar asked Jan 18 '13 21:01

Alfo


1 Answers

Use Ruby's URI module:

require 'uri'
URI.parse('http://www.example.com/page').host
=> "www.example.com"
URI.parse('http://blog.example.com/page').host
=> "blog.example.com"

In both cases, URI extracts the whole host name, because selectively stripping the host from the domain makes no sense.

You'll have to implement that logic separately, using something like:

%w[http://www.example.com/page http://blog.example.com/page].each do |u|
  puts URI.parse(u).host.sub(/^www\./, '')
end

Which outputs:

example.com
blog.example.com
like image 152
the Tin Man Avatar answered Oct 25 '22 23:10

the Tin Man