2013-08-16 61 views
1

我有紅寶石一個結構,看起來像這樣:轉換紅寶石結構來YAML

Struct.new("Device", :brand, :model, :port_id) 
@devices = [ 
Struct::Device.new('Apple', 'iphone5', 3), 
Struct::Device.new('Samsung', 'Galaxy S4', 1) 
] 

轉換這個to_yaml給了我這樣的結果:

--- 
- !ruby/struct:Struct::Device 
    brand: Apple 
    model: iphone5 
    port_id: 3 
- !ruby/struct:Struct::Device 
    brand: Samsung 
    model: Galaxy S4 
    port_id: 1 

但是我仍然不知道如何當我需要在我的代碼中使用它時,將我的結構從yaml轉換回來。當我在yaml代碼的頂部添加devices:,然後嘗試從CONFIG ['devices']變量解析回ruby結構 - 我沒有得到任何結果。

任何幫助將不勝感激!

回答

3

我沒有看到你的問題:

irb(main):001:0> require 'yaml' 
=> true 
irb(main):002:0> Struct.new("Device", :brand, :model, :port_id) 
=> Struct::Device 
irb(main):003:0> devices = [ 
irb(main):004:1* Struct::Device.new('Apple', 'iphone5', 3), 
irb(main):005:1* Struct::Device.new('Samsung', 'Galaxy S4', 1) 
irb(main):006:1> ] 
=> [#<struct Struct::Device brand="Apple", model="iphone5", port_id=3>, #<struct Struct::Device brand="Samsung", model="Galaxy S4", port_id=1>] 
irb(main):007:0> y = devices.to_yaml 
=> "---\n- !ruby/struct:Struct::Device\n brand: Apple\n model: iphone5\n port_id: 3\n- !ruby/struct:Struct::Device\n brand: Samsung\n model: Galaxy S4\n port_id: 1\n" 
irb(main):008:0> obj = YAML::load(y) 
=> [#<struct Struct::Device brand="Apple", model="iphone5", port_id=3>, #<struct Struct::Device brand="Samsung", model="Galaxy S4", port_id=1>] 

你必須確保在YAML::loadStruct.new運行以及前.to_yaml。否則,Ruby不知道如何從文本創建結構。

好吧,正如我所說的,您必須在嘗試加載之前運行Struct定義。另外,您正在試圖建立一個哈希,所以使用YAML語法:

config.yml

--- 
devices: 
- !ruby/struct:Struct::Device 
    brand: Apple 
    model: iphone5 
    port_id: 3 
- !ruby/struct:Struct::Device 
    brand: Samsung 
    model: Galaxy S4 
    port_id: 1 

而且test.rb

require 'yaml' 
Struct.new("Device", :brand, :model, :port_id) 
CONFIG = YAML::load_file('./config.yml') unless defined? CONFIG 
devices = CONFIG['devices'] 
puts devices.inspect 

結果:

C:\>ruby test.rb 
[#<struct Struct::Device brand="Apple", model="iphone5", port_id=3>, #<struct Struct::Device brand="Samsung", model="Galaxy S4", port_id=1>] 
+0

謝謝,我猜我的問題更像是這樣的: 如果我最初有yaml結構fo我的config.yml文件中的rmat如何正確讀取它? 我現在有它的方式是這樣的: config.yml '設備: - 紅寶石/結構:結構::設備 品牌:蘋果 型號:iphone5的 port_id:3 - 紅寶石/結構:結構::設備 品牌:三星型號 :銀河S4 port_id:1' test.rb '需要 'YAML' CONFIG = YAML.load_file( './ config.yml')另有定義的? CONFIG devices = CONFIG ['devices'] 然後當我執行'puts devices'時,我無法得到任何結果。 – sylvian

+0

對不起,我猜新行不在評論部分 – sylvian

+0

@ user2175891您應該閱讀答案!你錯過了'Struct'定義。在嘗試加載之前,這是必需的。也是YAML的一個小問題。看到我的附加代碼。 – Gene