Ruby Convert String to Hash

16,130

Solution 1

You can use eval(@data), but really it would be better to use a safer and simpler data format like JSON.

Solution 2

You can try YAML.load method

Example:

 YAML.load("{test: 't_value'}")

This will return following hash.

 {"test"=>"t_value"}

You can also use eval method

Example:

 eval("{test: 't_value'}")

This will also return same hash

  {"test"=>"t_value"} 

Hope this will help.

Solution 3

I would to this using the json gem.

In your Gemfile you use

gem 'json'

and then run bundle install.

In your program you require the gem.

require 'json'

And then you may create your "Hashfield" string by doing:

hash_as_string = hash_object.to_json

and write this to your flat file.

Finally, you may read it easily by doing:

my_hash = JSON.load(File.read('your_flat_file_name'))

This is simple and very easy to do.

Share:
16,130
user3063045
Author by

user3063045

Updated on June 27, 2022

Comments

  • user3063045
    user3063045 almost 2 years

    I'm storing configuration data in hashes written in flat files. I want to import the hashes into my Class so that I can invoke corresponding methods.

    example.rb

    { 
      :test1 => { :url => 'http://www.google.com' }, 
      :test2 => {
        { :title => 'This' } => {:failure => 'sendemal'}
      }
    }
    

    simpleclass.rb

    class Simple
      def initialize(file_name)
        # Parse the hash
        file = File.open(file_name, "r")
        @data = file.read
        file.close
      end
    
      def print
        @data
      end
    
    a = Simple.new("simpleexample.rb")
    b = a.print
    puts b.class   # => String
    

    How do I convert any "Hashified" String into an actual Hash?