Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `URI` and `URI.parse`

Tags:

url

uri

ruby

What is the difference between URI and URI.parse? Here is what I get:

require 'uri'
x = "http://google.com"
y = URI(x)       # => #<URI::HTTP http://google.com>
z = URI.parse(x) # => #<URI::HTTP http://google.com>
y == z # => true

I see in the docs that a new instance of URI creates a new URI::Generic instance from generic components without check, and that it has a default parser in the args.

The general recommendation seems to be URI.parse, and I am wondering why. I am wondering if there are any gotchas for using URI and not using URI.parse. Appreciate any insight.

Related: How to Parse a URL, Parse URL to Get Main Domain, Extract Host from URL string.

like image 944
nrako Avatar asked Mar 09 '15 15:03

nrako


1 Answers

Actually, URI(x) and URI.parse(x) are the same.

URI is a method defined on Kernel, which basically calls URI.parse(x).

We can confirm this by looking at the source code of the URI() method:

def URI(uri)
  if uri.is_a?(URI::Generic)
    uri
  elsif uri = String.try_convert(uri)
    URI.parse(uri)
  else
    raise ArgumentError,
      "bad argument (expected URI object or URI string)"
  end
end

Later, in your code, the ruby parser figures out if you actually want to have a function called URI or the module URI depending on the syntax you use.

like image 51
tessi Avatar answered Oct 21 '22 02:10

tessi