2016-11-12 144 views
2

我將配置數據存儲在用平面文件寫入的散列中。我想將哈希值導入到我的類中,以便可以調用相應的方法。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」 字符串轉換成實際的哈希?

+1

我會將它存儲爲JSON,讀取文件並使用'JSON.parse' – 23tux

+2

使用YML(yaml)或JSON將散列存儲在文件中,並將其作爲實際數據結構在ruby文件中讀取。 – Sivalingam

回答

7

您可以使用eval(@data),但實際上最好使用更安全,更簡單的數據格式,如JSON。

1

我會這樣使用JSON寶石。

在你的Gemfile您使用

gem 'json' 

,然後運行bundle install

在你的程序中,你需要寶石。

require 'json' 

然後,你可以通過做創建 「Hashfield」 字符串:

hash_as_string = hash_object.to_json 

寫給你的平面文件。

最後,你可以這樣做很容易閱讀:

my_hash = JSON.load(File.read('your_flat_file_name')) 

這是簡單,很容易做到。

0

如果不清楚,它只是必須包含在JSON文件中的散列。假設文件是​​ 「simpleexample.json」:

puts File.read("simpleexample.json") 
    # #{"test1":{"url":"http://www.google.com"},"test2":{"{:title=>\"This\"}":{"failure":"sendemal"}}} 

的代碼可以在一個正常的Ruby源代碼文件, 「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 

那麼我們可以這樣寫:

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 

h = { :test1=>{ :url=>'http://www.google.com' }, 
     :test2=>{ { :title=>'This' }=>{:failure=>'sendemal' } } } 

要從哈希構建JSON文件

我們寫:

File.write("simpleexample.json", JSON.generate(h)) 
    #=> 95 
2

您可以嘗試YAML.load方法

例子:

YAML.load("{test: 't_value'}") 

這將返回以下散。

{"test"=>"t_value"} 

您還可以使用EVAL方法

例子:

eval("{test: 't_value'}") 

這也將返回相同的哈希

{"test"=>"t_value"} 

希望這會有所幫助。