Struct 将ruby结构转换为yaml
我在ruby中有一个结构,如下所示:Struct 将ruby结构转换为yaml,struct,yaml,Struct,Yaml,我在ruby中有一个结构,如下所示: Struct.new("Device", :brand, :model, :port_id) @devices = [ Struct::Device.new('Apple', 'iphone5', 3), Struct::Device.new('Samsung', 'Galaxy S4', 1) ] 将其转换为_yaml会得到以下结果: --- - !ruby/struct:Struct::Device brand: Apple model:
Struct.new("Device", :brand, :model, :port_id)
@devices = [
Struct::Device.new('Apple', 'iphone5', 3),
Struct::Device.new('Samsung', 'Galaxy S4', 1)
]
将其转换为_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 struct时,我没有得到任何结果
任何帮助都将不胜感激 我没有看到你的问题:
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>]
和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>]
C:\>ruby test.rb
[#, #]
谢谢,我想我的问题更像这样:如果我最初在config.yml文件中有yaml格式的结构,我如何正确读取它?我现在的方式是这样的:config.ymldevices:-!ruby/struct:struct::设备品牌:苹果型号:iphone5端口号:3-!ruby/struct:struct::设备品牌:三星型号:Galaxy S4端口id:1
test.rbrequire'yaml'CONFIG=yaml.load_文件('./CONFIG.yml'),除非定义?CONFIG devices=CONFIG['devices']然后当我放置设备时,
put devices`我无法得到任何结果。@user2175891您应该阅读答案!您缺少Struct
定义。这是您尝试加载之前需要的。这也是YAML的一个小问题。请参阅我的附加代码。@user2175891如果答案有用,最好接受它。
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>]