码迷,mamicode.com
首页 > 其他好文 > 详细

ruby URI类

时间:2018-04-16 18:29:30      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:fragment   har   .com   name   char   method   方法   encode   url   

一. URI

require uri

uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#=> #<URI::HTTP:0x00000000b14880
      URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
uri.scheme
#=> "http"
uri.host
#=> "foo.com"
uri.path
#=> "/posts"
uri.query
#=> "id=30&limit=5"
uri.fragment
#=> "time=1305298413"

uri.to_s
#=> "http://foo.com/posts?id=30&limit=5#time=1305298413"

二. 常用方法

  • encode_www_form(enum, enc=nil)

    URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
    #=> "q=ruby&lang=en"
    URI.encode_www_form("q" => "ruby", "lang" => "en")
    #=> "q=ruby&lang=en"
    URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
    #=> "q=ruby&q=perl&lang=en"
    URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
    #=> "q=ruby&q=perl&lang=en"

     

  • decode_www_form(str, enc=Encoding::UTF_8, separator: ‘&‘, use__charset_: false, isindex: false)

    ary = URI.decode_www_form("a=1&a=2&b=3")
    p ary                  #=> [[‘a‘, ‘1‘], [‘a‘, ‘2‘], [‘b‘, ‘3‘]]
    p ary.assoc(a).last  #=> ‘1‘
    p ary.assoc(b).last  #=> ‘3‘
    p ary.rassoc(a).last #=> ‘2‘
    p Hash[ary]            # => {"a"=>"2", "b"=>"3"}

     

     

    相当于对请求字符串进行编解码

ruby URI类

标签:fragment   har   .com   name   char   method   方法   encode   url   

原文地址:https://www.cnblogs.com/wf0117/p/8856429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!