9

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?

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
user3063045
  • 2,019
  • 2
  • 22
  • 35

4 Answers4

13

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

David Grayson
  • 84,103
  • 24
  • 152
  • 189
4

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.

Amol Udage
  • 2,917
  • 19
  • 27
2

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.

Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57
0

Should it not be clear, it is only the hash that must be contained in a JSON file. Suppose that file is "simpleexample.json":

puts File.read("simpleexample.json")
  # #{"test1":{"url":"http://www.google.com"},"test2":{"{:title=>\"This\"}":{"failure":"sendemal"}}}

The code can be in a normal Ruby source file, "simpleclass.rb":

puts File.read("simpleclass.rb")
  # class Simple
  #   def initialize(example_file_name)
  #     @data = JSON.parse(File.read(example_file_name))
  #   end
  #   def print
  #     @data
  #   end
  # end

Then we can write:

require 'json'
require_relative "simpleclass"

a = Simple.new("simpleexample.json")
  #=> #<Simple:0x007ffd2189bab8 @data={"test1"=>{"url"=>"http://www.google.com"},
  #     "test2"=>{"{:title=>\"This\"}"=>{"failure"=>"sendemal"}}}> 
a.print
  #=> {"test1"=>{"url"=>"http://www.google.com"},
  #    "test2"=>{"{:title=>\"This\"}"=>{"failure"=>"sendemal"}}} 
a.class
  #=> Simple 

To construct the JSON file from the hash:

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

we write:

File.write("simpleexample.json", JSON.generate(h))
  #=> 95 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100