user3063045
user3063045

Reputation: 2209

Ruby Convert String to Hash

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?

Upvotes: 9

Views: 20483

Answers (4)

Amol Udage
Amol Udage

Reputation: 3075

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.

Upvotes: 4

Cary Swoveland
Cary Swoveland

Reputation: 110735

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 

Upvotes: 0

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.

Upvotes: 2

David Grayson
David Grayson

Reputation: 87486

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

Upvotes: 13

Related Questions