Ruby: How to turn a hash into HTTP parameters?

后端 未结 14 1580
故里飘歌
故里飘歌 2020-12-07 06:46

That is pretty easy with a plain hash like

{:a => \"a\", :b => \"b\"} 

which would translate into

\"a=a&b=b\"
<         


        
14条回答
  •  無奈伤痛
    2020-12-07 07:50

    For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query.

    >> {:a => "a", :b => ["c", "d", "e"]}.to_query
    => "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
    >> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
    => "a=a&b[]=c&b[]=d&b[]=e"
    

    http://api.rubyonrails.org/classes/Object.html#method-i-to_query

提交回复
热议问题