我將配置數據存儲在用平面文件寫入的散列中。我想將哈希值導入到我的類中,以便可以調用相應的方法。Ruby將字符串轉換爲散列
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
如何轉換任何 「Hashified」 字符串轉換成實際的哈希?
我會將它存儲爲JSON,讀取文件並使用'JSON.parse' – 23tux
使用YML(yaml)或JSON將散列存儲在文件中,並將其作爲實際數據結構在ruby文件中讀取。 – Sivalingam