1

我有以下示例字符串:

"email=bob@example.com&user_id=13&last_seen=January 14, 2013"

我需要转换为哈希:

{ :email=>bob@example.com, :user_id=>13, :last_seen => 'January 14, 2013' }

我怎样才能做到这一点?键和值可以是任何东西(它们并不总是emailand user_id)并且可能有几十个。

4

3 回答 3

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"}
于 2013-05-22T15:36:01.633 回答
2
str = "email=bob@example.com&user_id=13&last_seen=January 14, 2013"
Hash[*str.split(/=|&/)]

如果你在 Rails 中,你可以用 来表示键Hash#symbolize_keys,否则你可以自己做。

于 2013-05-22T15:25:06.957 回答
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"}
于 2013-06-29T14:38:15.170 回答