这对于普通哈希来说很简单

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

这就意味着

"a=a&b=b"

但是你怎么处理更复杂的东西,比如

{:a => "a", :b => ["c", "d", "e"]} 

这应该转化为

"a=a&b[0]=c&b[1]=d&b[2]=e" 

或者更糟的是,(该怎么做)像这样的事情:

{:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]

非常感谢你的帮助!


当前回答

如果你只需要支持简单的ASCII键/值查询字符串,这里有一个简短而甜蜜的语句:

hash = {"foo" => "bar", "fooz" => 123}
# => {"foo"=>"bar", "fooz"=>123}
query_string = hash.to_a.map { |x| "#{x[0]}=#{x[1]}" }.join("&")
# => "foo=bar&fooz=123"

其他回答

我知道这是一个老问题,但我只是想张贴这段代码,因为我找不到一个简单的宝石来为我做这个任务。

module QueryParams

  def self.encode(value, key = nil)
    case value
    when Hash  then value.map { |k,v| encode(v, append_key(key,k)) }.join('&')
    when Array then value.map { |v| encode(v, "#{key}[]") }.join('&')
    when nil   then ''
    else            
      "#{key}=#{CGI.escape(value.to_s)}" 
    end
  end

  private

  def self.append_key(root_key, key)
    root_key.nil? ? key : "#{root_key}[#{key.to_s}]"
  end
end

在这里汇总为宝石:https://github.com/simen/queryparams

更新:此功能已从gem中移除。

朱利安,你自己的回答很好,我无耻地借鉴了它,但它不能正确地逃脱保留字符,还有一些其他的边缘情况,它会崩溃。

require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
uri.query
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
uri.query
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
uri.query
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
uri.query
# => "a=a&b[c]=c&b[d]"

宝石是“可寻址的”

gem install addressable

如果你在法拉第请求的上下文中,你也可以只是传递params哈希作为第二个参数,法拉第会照顾到正确的param URL部分:

faraday_instance.get(url, params_hsh)
{:a=>"a", :b=>"b", :c=>"c"}.map{ |x,v| "#{x}=#{v}" }.reduce{|x,v| "#{x}&#{v}" }

"a=a&b=b&c=c"

还有另一种方法。对于简单的查询。

我喜欢使用这个宝石:

https://rubygems.org/gems/php_http_build_query

示例用法:

puts PHP.http_build_query({"a"=>"b","c"=>"d","e"=>[{"hello"=>"world","bah"=>"black"},{"hello"=>"world","bah"=>"black"}]})

# a=b&c=d&e%5B0%5D%5Bbah%5D=black&e%5B0%5D%5Bhello%5D=world&e%5B1%5D%5Bbah%5D=black&e%5B1%5D%5Bhello%5D=world