Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Convert String to Hash

Tags:

ruby

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?

like image 706
user3063045 Avatar asked Nov 12 '16 20:11

user3063045


2 Answers

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

like image 73
David Grayson Avatar answered Nov 15 '22 23:11

David Grayson


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.

like image 28
Amol Udage Avatar answered Nov 15 '22 21:11

Amol Udage