1

我在 ruby​​ 中有一个如下所示的结构:

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 转换回来。当我devices:在 yaml 代码之上添加然后尝试从 CONFIG['devices'] 变量将其解析回 ruby​​ 结构时 - 我没有得到任何结果。

任何帮助将不胜感激!

4

1 回答 1

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>]

您必须确保在Struct.new之前YAML::load以及在 之前运行.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>]
于 2013-08-16T01:33:11.977 回答