Created
March 27, 2014 09:48
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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