将字符串拆分成哈希?

时间:2013-05-22 15:23:09

标签: ruby string hash

我有以下示例字符串:

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

我需要转换为哈希:

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

我该怎么做?键和值可以是任何值(它们不总是emailuser_id),并且可能有数十个。

3 个答案:

答案 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"}