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

后端 未结 5 1770
遇见更好的自我
遇见更好的自我 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:24

    Quick Hash to a URL Query Trick :

    "http://www.example.com?" + { language: "ruby", status: "awesome" }.to_query
    
    # => "http://www.example.com?language=ruby&status=awesome"
    

    Want to do it in reverse? Use CGI.parse:

    require 'cgi' 
    # Only needed for IRB, Rails already has this loaded
    
    CGI::parse "language=ruby&status=awesome"
    
    # => {"language"=>["ruby"], "status"=>["awesome"]} 
    
    0 讨论(0)
  • 2021-02-13 17:26

    Here's a quick function to turn your hash into query parameters:

    require 'uri'
    def hash_to_query(hash)
      return URI.encode(hash.map{|k,v| "#{k}=#{v}"}.join("&"))
    end
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-13 17:40

    In modern ruby this is simply:

    require 'uri'
    URI.encode_www_form(hash)
    
    0 讨论(0)
  • 2021-02-13 17:49

    The way rails handles query strings of that type means you have to roll your own solution, as you have. It is somewhat unfortunate if you're dealing with non-rails apps, but makes sense if you're passing information to and from rails apps.

    0 讨论(0)
提交回复
热议问题