像 Ruby on Rails 中的查询字符串一样解析字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2772778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse a string as if it were a querystring in Ruby on Rails
提问by Julik
I have a string like this:
我有一个这样的字符串:
"foo=bar&bar=foo&hello=hi"
Does Ruby on Rails provide methods to parse this as if it is a querystring, so I get a hash like this:
Ruby on Rails 是否提供了解析它的方法,就好像它是一个查询字符串一样,所以我得到一个这样的哈希:
{
:foo => "bar",
:bar => "foo",
:hello => "hi"
}
Or must I write it myself?
还是必须自己写?
EDIT
编辑
Please note that the string above is not a real querystring from a URL, but rather a string stored in a cookie from Facebook Connect.
请注意,上面的字符串不是来自 URL 的真实查询字符串,而是存储在 Facebook Connect cookie 中的字符串。
回答by Julik
The answer depends on the version of Rails that you are using. If you are using 2.3 or later, use Rack's builtin parser for params
答案取决于您使用的 Rails 版本。如果您使用的是 2.3 或更高版本,请使用 Rack 的内置解析器来获取参数
Rack::Utils.parse_nested_query("a=2") #=> {"a" => "2"}
If you are on older Rails, you can indeed use CGI::parse. Note that handling of hashes and arrays differs in subtle ways between modules so you need to verify whether the data you are getting is correct for the method you choose.
如果您使用的是较旧的 Rails,则确实可以使用CGI::parse. 请注意,散列和数组的处理在模块之间以微妙的方式不同,因此您需要验证您获得的数据对于您选择的方法是否正确。
You can also include Rack::Utilsinto your class for shorthand access.
您还可以将其包含Rack::Utils到您的类中以进行速记访问。
回答by dombesz
The
这
CGI::parse("foo=bar&bar=foo&hello=hi")
Gives you
给你
{"foo"=>["bar"], "hello"=>["hi"], "bar"=>["foo"]}
回答by systho
Edit :as said in the comments, symolizing keys can bring your server down if someone want to hurt you. I still do it a lot when I work on low profile apps because it makes things easier to work with but I wouldn't do it anymore for high stake apps
编辑:如评论中所述,如果有人想伤害您,符号化键可以使您的服务器停机。当我在低调的应用程序上工作时,我仍然经常这样做,因为它使事情更容易使用,但我不会再为高风险的应用程序做这件事了
Do not forget to symbolize the keys for obtaining the result you want
不要忘记符号化获得你想要的结果的关键
Rack::Utils.parse_nested_query("a=2&b=tralalala").deep_symbolize_keys
this operation is destructive for duplicates.
此操作对重复项具有破坏性。
回答by lokeshjain2008
If you talking about the Urls that is being used to get data about the parameters them
如果您谈论的是用于获取有关它们的参数的数据的 Urls
> request.url
=> "http://localhost:3000/restaurants/lokesh-dhaba?data=some&more=thisIsMore"
Then to get the query parameters. use
然后获取查询参数。用
> request.query_parameters
=> {"data"=>"some", "more"=>"thisIsMore"}
回答by Arnold Roa
If you want a hash you can use
如果你想要一个散列,你可以使用
Hash[CGI::parse(x).map{|k,v| [k, v.first]}]

