[英]String to Hash conversion
我如何将字符串转换为哈希?
现在我用:
eval "{'1627207:28320'=>'text'}"
=> {'1627207:28320'=>'text'}
但是“ eval”不适用于我的情况-从params传递字符串,并且这种情况不安全
编辑:
传递的字符串也可以是:
"{'1627207'=>'text', '11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}"
然后需要结果哈希:
{'1627207:28320'=>'text',
'11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}
str = "{'1627207:28320'=>'text'}"
p Hash[*str.delete("{}'").split('=>')] #{"1627207:28320"=>"text"}
编辑不同的输入:
str = "{'1627207:28320'=>'text', 'key2'=>'text2'}"
p Hash[*str.delete("{}'").split(/=>|, /)] #{"1627207:28320"=>"text", "key2"=>"text2"}
class String
def to_h
h={}
self.scan(/'(\w+.\w+)'=>'(\w+)'/).each { |k,v| h[k]=v }
h
end
end
p "{'1627207:28320'=>'text','test'=>'text2'}".to_h
=>{"1627207:28320"=>"text", "test"=>"text2"}
编辑:较短的版本
class String
def to_h
Hash[self.scan(/'([^']+)'=>'([^']+)'/)]
end
end
很直接:
$ irb
irb(main):001:0> k='1627207:28320'
=> "1627207:28320"
irb(main):002:0> v='text'
=> "text"
irb(main):003:0> h={k => v}
=> {"1627207:28320"=>"text"}
irb(main):004:0> h
=> {"1627207:28320"=>"text"}
irb(main):005:0>
您可以尝试以下操作:
text_hash['1627207:28320'] = 'text'
text_hash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.