将字符串解析为Ruby中的哈希值

问题描述 投票:0回答:1

我正在尝试将ruby中的字符串解析为哈希,但是我不太清楚。我已经将它放置到一个嵌套数组中,只需要将其映射到哈希即可。

示例字符串

subject = "{\"CN\"=\"schoen.io\", \"C\"=\"US\", \"ST\"=\"Texas\", \"L\"=\"North Doyle\", \"O\"=\"SSL Corporation\", \"OU\"=\"Information Technology Department\", \"2.5.4.17\"=\"16039-4645\", \"2.5.4.9\"=\"8268 Kemmer Village\", \"2.5.4.42\"=\"Tracy\", \"2.5.4.4\"=\"Jacobi\", \"2.5.4.5\"=\"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx\", \"2.5.29.17\"=\"ssl.com\"}}"

所需的哈希

{'CN' => 'schoen.io', 'C' => 'US', 'ST' => 'Texas',... }

我的代码] >>

subject.gsub('{','').gsub('}','').split(',').map { |m| m.split('=')}

[generated array

] >>
[["\"CN\"", "\"schoen.io\""], [" \"C\"", "\"US\""], [" \"ST\"", "\"Texas\""], [" \"L\"", "\"North Doyle\""], [" \"O\"", "\"SSL Corporation\""], [" \"OU\"", "\"Information Technology Department\""], [" \"2.5.4.17\"", "\"16039-4645\""], [" \"2.5.4.9\"", "\"8268 Kemmer Village\""], [" \"2.5.4.42\"", "\"Tracy\""], [" \"2.5.4.4\"", "\"Jacobi\""], [" \"2.5.4.5\"", "\"grbh52f84senk4jkgo9n9a66yg62w78y4a0v36ax8tfacdshublxjpq6arcn7qyx\""], [" \"2.5.29.17\"", "\"ssl.com\""]]

我正在尝试将ruby中的字符串解析为哈希,但是我不太清楚。我已经将其添加到嵌套数组中,只需要将其映射到哈希即可。示例字符串subject =“ {\” CN \“ = \” schoen.io \“,\” C \ ...

arrays ruby string hash
1个回答
0
投票

我认为您的原始主题有错别字。字符串的末尾有两个},而开头只有一个。

如果删除它,您的字符串现在为:

© www.soinside.com 2019 - 2024. All rights reserved.