我有以下示例字符串:
"email=bob@example.com&user_id=13&last_seen=January 14, 2013"
我需要转换为哈希:
{ :email=>bob@example.com, :user_id=>13, :last_seen => 'January 14, 2013' }
我该怎么做?键和值可以是任何值(它们不总是email
和user_id
),并且可能有数十个。
答案 0 :(得分:7)
使用您已免费获得的CGI库:
require 'cgi'
parsed = CGI.parse("email=bob@example.com&user_id=13&last_seen=January 14, 2013")
# => {"email"=>["bob@example.com"], "user_id"=>["13"], "last_seen"=>["January 14, 2013"]}
或者,如果您使用rack:
require 'rack/utils'
parsed = Rack::Utils.parse_query("email=bob@example.com&user_id=13&last_seen=January 14, 2013")
# => {"email"=>"bob@example.com", "user_id"=>"13", "last_seen"=>"January 14, 2013"}
答案 1 :(得分:2)
str = "email=bob@example.com&user_id=13&last_seen=January 14, 2013"
Hash[*str.split(/=|&/)]
如果您使用的是Rails,则可以使用Hash#symbolize_keys
对按键进行符号化处理,否则您可以自行完成。
答案 2 :(得分:0)
下面怎么样:
require 'uri'
str = "email=bob@example.com&user_id=13&last_seen=January 14, 2013"
URI.decode_www_form(str)
# => [["email", "bob@example.com"],
# ["user_id", "13"],
# ["last_seen", "January 14, 2013"]]
Hash[URI.decode_www_form(str)]
# => {"email"=>"bob@example.com",
# "user_id"=>"13",
# "last_seen"=>"January 14, 2013"}