简体   繁体   English

字符串到哈希的转换

[英]String to Hash conversion

How i can convert string into hash? 我如何将字符串转换为哈希?

now i use: 现在我用:

eval "{'1627207:28320'=>'text'}"
=> {'1627207:28320'=>'text'}

but "eval" is not good for my case - string passed from params, and such case it is not secure 但是“ eval”不适用于我的情况-从params传递字符串,并且这种情况不安全

Edited: 编辑:

passed string can also be: 传递的字符串也可以是:

"{'1627207'=>'text', '11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}"

Then need result hash: 然后需要结果哈希:

{'1627207:28320'=>'text',
'11:167:28320'=>'text 1 / text 2 / unicode=>привет!'}
str = "{'1627207:28320'=>'text'}"
p Hash[*str.delete("{}'").split('=>')] #{"1627207:28320"=>"text"}

edit for different input: 编辑不同的输入:

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

EDIT: shorter version 编辑:较短的版本

class String
  def to_h
    Hash[self.scan(/'([^']+)'=>'([^']+)'/)]
  end
end

Quite straight forward: 很直接:

$ 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>

You could simply try this: 您可以尝试以下操作:

text_hash['1627207:28320'] = 'text'
text_hash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM