我有以下示例字符串:
"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
and user_id
)并且可能有几十个。
使用您已经免费获得的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"}
str = "email=bob@example.com&user_id=13&last_seen=January 14, 2013"
Hash[*str.split(/=|&/)]
如果你在 Rails 中,你可以用 来表示键Hash#symbolize_keys
,否则你可以自己做。
下面怎么样:
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"}