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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With