字符串哈希转换 [英] String to Hash conversion

查看:146
本文介绍了字符串哈希转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串转换为散列?



现在我使用:

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

但eval不适合我的情况 - 从params传递的字符串,这种情况下它是不安全的

编辑:



传递的字符串也可以是:
$ b

{'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(/ => |,/)]#{1 627207:28320=>text,key2=>text2}


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

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

这篇关于字符串哈希转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆