I have ugly string that looks like this:
"\"New\"=>\"0\""
Which will be the best way to converting it into hash object?
I have ugly string that looks like this:
"\"New\"=>\"0\""
Which will be the best way to converting it into hash object?
Problem with "\"New\"=>\"0\""
is it does not look like a Hash. So first step should be to manipulate it to look like a Hash:
"{" + a + "}"
# => "{\"New\"=>\"0\"}"
Now once you have a hash looking string you can convert it into Hash like this:
eval "{" + a + "}"
# => {"New"=>"0"}
However there is still one issue, eval
is not safe and inadvisable to use. So lets manipulate the string further to make it look json-like and use JSON.parse
:
require `json`
JSON.parse ("{" + a + "}").gsub("=>",":")
# => {"New"=>"0"}
How about JSON.parse(string.gsub("=>", ":"))
You can use regex to pull out the key and value. Then create Hash
directly
Hash[*"\"New\"=>\"0\"".scan(/".*?"/)]
Hard to nail down the best way if you can't tell us exactly the general format of those strings. You may not even need the regex. eg
Hash[*"\"New\"=>\"0\"".split('"').values_at(1,3)]
Also works for "\"Rocket\"=>\"=>\""