0

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.

2
  • Why do you want to convert it to YAML first, instead of simply loading it into an array? Commented Aug 29, 2012 at 1:09
  • The YAML docs for Ruby are extremely easy to read and understand. Commented Aug 29, 2012 at 1:36

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.