converting ruby struct to yaml -
i have struct in ruby looks this:
struct.new("device", :brand, :model, :port_id) @devices = [ struct::device.new('apple', 'iphone5', 3), struct::device.new('samsung', 'galaxy s4', 1) ]
converting to_yaml gives me result:
--- - !ruby/struct:struct::device brand: apple model: iphone5 port_id: 3 - !ruby/struct:struct::device brand: samsung model: galaxy s4 port_id: 1
however i'm still not sure how convert struct yaml whenever need use in code. when add devices:
on top of yaml code , try parse ruby struct config['devices'] variable - don't results.
any appreciated!
i'm not seeing problem:
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>]
you must make sure struct.new
runs before yaml::load
before .to_yaml
. otherwise ruby doesn't know how create struct text.
okay, said, must run struct definition before trying load. plus trying build hash, use yaml syntax:
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
and 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
result:
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>]
Comments
Post a Comment