Reputation: 967
I have sets of data like this:
5.3.12.0
5.3.12.1
5.3.12.2
5.3.12.3
5.3.12.4
How do I structure this in a YAML file, and then load it into Ruby as a simple array?
I want the data above to be loaded as an array like:
fileset_levels = ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3", "5.3.12.4"]
I'll have multiple sets of these arrays I want to load, so I want to have files called:
vuln1.yml
vuln2.yml
and have them all load as arrays I can use in my Ruby script.
I've tried:
vuln1_array = yaml::load("vuln1.yml")
but it does not create the array.
Upvotes: 0
Views: 2038
Reputation: 160631
A great way to learn how to do anything with a serializer is to try writing a piece of code to demo a round-trip:
require 'yaml'
puts %w[
5.3.12.0
5.3.12.1
5.3.12.2
5.3.12.3
5.3.12.4
].to_yaml
Which outputs:
---
- 5.3.12.0
- 5.3.12.1
- 5.3.12.2
- 5.3.12.3
- 5.3.12.4
Creating the round-trip looks like:
require 'pp'
require 'yaml'
pp YAML.load(
%w[
5.3.12.0
5.3.12.1
5.3.12.2
5.3.12.3
5.3.12.4
].to_yaml
)
which now outputs:
=> ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3", "5.3.12.4"]
The advantage to this process is you see what it should look like, and learn how to parse it.
I use a similar process to generate complex YAML documents used for configuration files. While we can create them from scratch, it's easier to use simple Ruby arrays and hashes, and then let YAML sort it all out as it generates its output. I redirect the output to a file and use that as the starting point.
Upvotes: 7
Reputation: 15010
you call this a yaml file but this is just a basic file. Yaml is like a hash structure, you have a key that match a value. Here just a list of values.
What you can do is
>> file = File.read('vuln1.yml')
=> "5.3.12.0\n5.3.12.1\n5.3.12.2\n5.3.12.3 \n5.3.12.4\n"
>> file.split("\n")
=> ["5.3.12.0", "5.3.12.1", "5.3.12.2", "5.3.12.3 ", "5.3.12.4"]
Upvotes: 2