Module URI constructor explain


Please briefly explain why you feel this question should be reported .

Report Cancel
require "uri"

u = URI.parse("")  #<URI::HTTPS>
v = URI("")        #<URI::HTTPS>
u == v                                   # => true

The URI.parse is easy to understand, it calls module_function parse on Module URI.

How to understand URI() in Ruby’s context? What method does it called? Or is this a syntactic sugar?

solved 0
1 Answer 23 views 0

Answer ( 1 )

    November 15, 2016 at 7:42 pm

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    Best answer on your question is source code. Code below executes when you call URI('http..')

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

    As you can see under the hood this method allows you to pass any argument and be sure that program will throw ArgumentError if argument wasn’t uri or instance of uri. So, in my opinion good practice to use URI('...') than URI.parse('...') with additional checks.

    Feel free to check it out by yourself: github ruby repo mirror

    Best answer

Leave an answer


What is the capital of Egypt ? ( Cairo )

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>