Is it possible to take YAML and turn it into a Struct? I want to take
something that looks like this:
key_1: Value 1
key_2: Value 2
And turn it into an object with accessors…and I’m assuming a Struct
would be my best bet. I’m relatively new to the concepts of YAML and
the Struct class, so I’m banging my head against the wall trying to
figure this out.
class Hash
def to_struct class_name = nil
klass =
unless class_name
Struct.new *keys.map{|key| key.to_sym}
else
Struct.new class_name.to_s, *keys.map{|key| key.to_sym}
end
klass.new *values
end
end
Is it possible to take YAML and turn it into a Struct? I want to take
something that looks like this:
key_1: Value 1
key_2: Value 2
And turn it into an object with accessors…and I’m assuming a Struct
would be my best bet. I’m relatively new to the concepts of YAML and
the Struct class, so I’m banging my head against the wall trying to
figure this out.
The easiest way is to create a MyStruct and add “— !ruby/
struct:MyStruct” to your YAML then use YAML.load. This way you can
round-trip without pain.
$ ruby
require ‘yaml’
MyStruct = Struct.new :key_1, :key_2
data = MyStruct.new ‘Value 1’, ‘Value 2’
yaml = data.to_yaml
puts yaml
newdata = YAML.load yaml
p newdata
— !ruby/struct:MyStruct
key_1: Value 1
key_2: Value 2
#<struct MyStruct key_1=“Value 1”, key_2=“Value 2”>
Is it possible to take YAML and turn it into a Struct? I want to take
something that looks like this:
key_1: Value 1
key_2: Value 2
And turn it into an object with accessors…and I’m assuming a Struct
would be my best bet. I’m relatively new to the concepts of YAML and
the Struct class, so I’m banging my head against the wall trying to
figure this out.
Any ideas?
I was able to achieve this using OpenStruct and two lines of code:
data = YAML::load(yaml_data).to_hash @item = OpenStruct.new(data)
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.