简体   繁体   中英

Difference between `URI` and `URI.parse`

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM