簡體   English   中英

字符串到哈希的轉換

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM