Skip to content

Instantly share code, notes, and snippets.

@cmthakur
Created March 27, 2014 09:48
Show Gist options
  • Select an option

  • Save cmthakur/9803963 to your computer and use it in GitHub Desktop.

Select an option

Save cmthakur/9803963 to your computer and use it in GitHub Desktop.
Change a given string that contains hash inside it to a hash object. Similar to eval(string_with_hash)
def convert_to_hash(string)
string.gsub(/[{}:]/,'').split(', ').inject({}) do |hash, str_value|
splitted_value = str_value.split('=>')
splitted_value.delete('')
key,value = splitted_value
if splitted_value.count > 2
new_str = str_value.split(key)
new_str.delete('')
value = convert_to_hash(new_str.last.to_s)
end
key.tr!('"', '')
value.tr!('"', '')
hash[key] = value
hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment