convert ruby hash to URL query string … without those square brackets

后端 未结 5 1771
遇见更好的自我
遇见更好的自我 2021-02-13 16:46

In Python, I can do this:

>>> import urlparse, urllib
>>> q = urlparse.parse_qsl(\"a=b&a=c&d=e\")
>>> urllib.urlencode(q)
\'a=         


        
5条回答
  •  广开言路
    2021-02-13 17:39

    As a simple plain Ruby solution (or RubyMotion, in my case), just use this:

    class Hash
      def to_param
        self.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
      end
    end
    
    { fruit: "Apple", vegetable: "Carrot" }.to_param # => "fruit=Apple&vegetable=Carrot"
    

    It only handles simple hashes, though.

提交回复
热议问题