2013-08-16 62 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