我没有看到你的问题:
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>]