I have this string and I'm wondering how to convert it to a Hash.
"{:account_id=>4444, :deposit_id=>3333}"
The way suggested in miku's answer is indeed easiest and unsafest.
# DO NOT RUN IT
eval '{:surprise => "#{system \"rm -rf / \"}"}'
# SERIOUSLY, DON'T
Consider using a different string representation of your hashes, e.g. JSON or YAML. It's way more secure and at least equally robust.
With a little replacement, you may use 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.
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, 'key3' => nil}}"
you can convert it into hash like this without using eval which is dangerous
desired_hash = JSON.parse(stringify_hash.gsub("'",'"').gsub('=>',':').gsub('nil','null'))
and for the one you posted where the key is a symbol you can use like this
JSON.parse(string_hash.gsub(':','"').gsub('=>','":'))
The easiest and unsafest would 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
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("=>")}]