ruby 如何解析哈希的字符串表示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8613976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:36:39  来源:igfitidea点击:

How to parse a string representation of a hash

rubyhash

提问by zoras

I have this string and I'm wondering how to convert it to a Hash.

我有这个字符串,我想知道如何将它转换为哈希。

"{:account_id=>4444, :deposit_id=>3333}"

采纳答案by zoras

Guess I never posted my workaround for this... Here it goes,

猜猜我从来没有为此发布过我的解决方法......它是这样的,

# strip the hash down
stringy_hash = "account_id=>4444, deposit_id=>3333"

# turn string into hash
Hash[stringy_hash.split(",").collect{|x| x.strip.split("=>")}]

回答by Jan

The way suggested in miku's answer is indeed easiest and unsafest.

miku 的回答中建议的方式确实是最简单和最不安全的

# DO NOT RUN IT
eval '{:surprise => "#{system \"rm -rf / \"}"}'
# SERIOUSLY, DON'T

Consider using a different string representation of your hashes, e.g. JSONor YAML. It's way more secure and at least equally robust.

考虑使用不同的哈希字符串表示形式,例如JSON或 YAML。它更安全,至少同样强大。

回答by knut

With a little replacement, you may use YAML:

稍加替换,您就可以使用 YAML:

require 'yaml'

p YAML.load(
  "{:account_id=>4444, :deposit_id=>3333}".gsub(/=>/, ': ')
  )

But this works only for this specific, simple string. Depending on your real data you may get problems.

但这仅适用于这个特定的简单字符串。根据您的真实数据,您可能会遇到问题。

回答by Mr. Bless

if your string hash is some sort of like this (it can be nested or plain hash)

如果你的字符串哈希是这样的(它可以是嵌套的或普通的哈希)

stringify_hash = "{'account_id'=>4444, 'deposit_id'=>3333, 'nested_key'=>{'key1' => val1, 'key2' => val2}}"

you can convert it into hash like this without using eval which is dangerous

您可以将其转换为这样的哈希,而无需使用危险的 eval

desired_hash = JSON.parse(stringify_hash.gsub("'",'"').gsub('=>',':'))

and for the one you posted where the key is a symbol you can use like this

对于您发布的键是符号的地方,您可以像这样使用

JSON.parse(string_hash.gsub(':','"').gsub('=>','":'))

回答by miku

The easiest and unsafestwould be to just evaluate the string:

最简单和最不安全的方法是只评估字符串:

>> s = "{:account_id=>4444, :deposit_id=>3333}"
>> h = eval(s)
=> {:account_id=>4444, :deposit_id=>3333}
>> h.class
=> Hash