O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.15. Parsing URLs

Problem

You want to parse a string representation of a URL into a data structure that articulates the parts of the URL.

Solution

URI.parse transforms a string describing a URL into a URI object.[5] The parts of the URL can be determined by interrogating the URI object.

	require 'uri'

	URI.parse('https://www.example.com').scheme           # => "https"
	URI.parse('http://www.example.com/').host             # => "www.example.com"
	URI.parse('http://www.example.com:6060/').port        # => 6060
	URI.parse('http://example.com/a/file.html').path      # => "/a/file.html"

URI.split transforms a string into an array of URL parts. This is more efficient than URI.parse, but you have to know which parts correspond to which slots in the array:

	URI.split('http://example.com/a/file.html')
	# => ["http", nil, "example.com", nil, nil, "/a/file.html", nil, nil, nil]

Discussion

The URI module contains classes for five of the most popular URI schemas. Each one can store in a structured format the data that makes up a URI for that schema. URI.parse creates an instance of the appropriate class for a particular URL's scheme.

Every URI can be decomposed into a set of components, joined by constant strings. For example: the components for a HTTP URI are the scheme ("http"), the hostname ("http://www.example.com (http://www.example.com)"), and so on. Each URI schema has its own components, and each of Ruby's URI classes stores the names of its components in an ordered array of symbols, called component:

 URI::HTTP.component # => ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required