Last active
          December 12, 2023 01:27 
        
      - 
      
- 
        Save just3ws/d002243983ae00886c37 to your computer and use it in GitHub Desktop. 
    Converting a string representation of a Ruby Hash back into a Ruby 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
    
  
  
    
  | require 'pp' | |
| require 'json' | |
| s = "{:exit_url=>\"null\", :exit_target_type=>\"left\", :furthest_scrolled=>\"locations\", :time_spent=>\"543210\", :user_id=>\"123456\", :visited_at=>789101112, :user=>nil}" | |
| pp JSON.parse("{" + s.gsub(/^{|}$/, '').split(', ').map { |pair| pair.split('=>') }.map {|k, v| [k.gsub(/^:(\w*)/, '"\1"'), v == 'nil' ? "null" : v].join(": ") }.join(", ") + "}") | |
| => {"exit_url"=>"null", "exit_target_type"=>"left", "furthest_scrolled"=>"locations", "time_spent"=>"543210", "user_id"=>"123456", "visited_at"=>789101112, "user"=>nil} | |
This is what I found:
def string_parse_to_hash(string)
  modified_string = string
    .gsub(/:(\w+)/){"\"#{$1}\""}
    .gsub('=>', ':')
    .gsub("nil", "null")
  JSON.parse(modified_string)
rescue
  {}
end
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
I hate this code but it's better than
eval. Any suggestions?