用一个简单的散列,比如

{: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"}]

非常感谢您在这方面给予的帮助!

推荐答案

Update:此功能已从gem中删除.

朱利安,你的self 回答很好,我无耻地borrow 了它,但它不能正确地避开保留字符,还有一些其他边缘 case ,它崩溃了.

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]"

Ruby 是"addressable"

gem install addressable

Ruby相关问答推荐

Ruby PKCS7:添加;\r〃;字节正在 destruct 解密

类似于模块的 attr_accessor 和 attr_reader 的东西?

有没有更好的方法来加入剩余不变的子列表?

VS Code Prettier 打破哈希访问

Kernel#gets try 读取文件而不是标准输入

在ruby中反转数组的顺序

Encoding::UndefinedConversionError

rbenv 没有显示可用的 ruby​​ 版本

在 ruby​​ 中访问嵌套哈希的元素

使用 Ruby MiniTest 之前/之后的套件

Ruby 中的关联数组

RSpec:如何测试文件操作和文件内容

Ruby中的常量或类变量?

Ruby 在特定目录中运行 shell 命令

Mountain Lion rvm 安装 1.8.7 x11 错误

如何在 Ruby 中将类构造函数设为私有?

从Ruby中的子类方法调用父类中的方法

Ruby 哈希白名单过滤器

为什么我们在 Ruby 中有 0.0 和 -0.0?

如何删除已安装的 ri 和 rdoc?