user3063045 user3063045 - 21 days ago 16
Ruby Question

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?

Answer

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

Comments