代码之家  ›  专栏  ›  技术社区  ›  oliver

如何在Ruby中将Scheme设置为URI对象

  •  15
  • oliver  · 技术社区  · 14 年前

    我正在尝试从用户输入解析一个URI。我假设一些用户不会将该方案放在他们的URI中,我希望默认为“http”。

    以下代码不起作用:

    require 'uri'   
    
    uri_to_check = URI::parse("www.google.com")
    uri_to_check.scheme = "http" unless uri_to_check.scheme
    
    puts uri_to_check.to_s
    

    我希望看到” http://www.google.com “但是我得到”http:www.google.com“。这样做有可能吗?

    如果是的话,我错过了什么?

    有更好的方法吗?

    2 回复  |  直到 14 年前
        2
  •  5
  •   Scolytus    14 年前

    URI

    irb(main):001:0> require 'uri'
    => true
    irb(main):002:0> uri = URI::parse("www.google.com")
    => #<URI::Generic:0x11cfc88 URL:www.google.com>
    irb(main):003:0> uri.path
    => "www.google.com"
    irb(main):004:0> uri.host
    => nil
    

    to_s

    uri = URI::parse("www.google.com")
    if uri.scheme.nil? && uri.host.nil?
      unless uri.path.nil?
        uri.scheme = "http"
        uri.host = uri.path
        uri.path = ""
      end
    end
    
    puts uri.to_s