Ruby将字符串转换为哈希

use*_*045 3 ruby hash

我将配置数据存储在以平面文件编写的哈希中.我想将哈希值导入我的类中,以便我可以调用相应的方法.

example.rb

{ 
  :test1 => { :url => 'http://www.google.com' }, 
  :test2 => {
    { :title => 'This' } => {:failure => 'sendemal'}
  }
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

如何将任何"Hashified"字符串转换为实际的哈希?

Dav*_*son 8

您可以使用eval(@data),但实际上最好使用更安全,更简单的数据格式,如JSON.