This question already has an answer here:
这个问题已经有了答案:
- Parse a string as if it were a querystring in Ruby on Rails 5 answers
- 将字符串解析为Ruby on Rails 5中的查询字符串
I want to create a hash from a querystring. This is my method:
我想从一个querystring创建一个散列。这是我的方法:
def qs2h(querystring)
hashes = querystring.split('&').inject({}) do |result,query|
k,v = query.split('=')
if !v.nil?
result.merge(k.to_sym => v)
elsif !result.key?(k)
result.merge(k.to_sym => true)
else
result
end
end
hashes
end
qs2h('a=1&b=2&c=3&d') #=> {:a => "1", :b => "2", :c => "3", :d => true}
Is there any simpler method to do this in ruby?
在ruby中有什么更简单的方法来实现这一点吗?
1 个解决方案
#1
7
Use CGI::parse
:
使用CGI::解析:
CGI.parse('a=1&b=2&c=3&d')
# => {"a"=>["1"], "b"=>["2"], "c"=>["3"], "d"=>[]}
Hash[CGI.parse('a=1&b=2&c=3&d').map {|key,values| [key.to_sym, values[0]||true]}]
# => {:a=>"1", :b=>"2", :c=>"3", :d=>true}
#1
7
Use CGI::parse
:
使用CGI::解析:
CGI.parse('a=1&b=2&c=3&d')
# => {"a"=>["1"], "b"=>["2"], "c"=>["3"], "d"=>[]}
Hash[CGI.parse('a=1&b=2&c=3&d').map {|key,values| [key.to_sym, values[0]||true]}]
# => {:a=>"1", :b=>"2", :c=>"3", :d=>true}