Reading data from a yaml file and creating an array in ruby

I have the following data in a yaml file -

--- - :Subject_list Subject 1: :Act 1: A :Act 2: B Subject 2: :Skill 1: :Act 1: B :Act 2: B :Skill 2: :Act 1: B 

I need to read the data from this file and generate the output that is given below - For subject 1, it will be like it does not have a skill level. The value of the first element of the array is null.

  ["","Act 1", "A"], ["","Act 2", "B"] 

For the second subject, it will be like this:

  ["Skill 1","Act 1", "B"], ["","Act 2" "B"],["Skill 2","Act 1", "B"] 

I use these values ​​to create a pdf prawn table. Any help is appreciated.

I tried to do this -

 data=YAML::load(File.read("file.yaml")); subject = data[:Subject_list] sub_list =["Subject 1", "Subject 2"] sub_list.each do |sub| sub_data = [] sub_data = subject["#{sub}"] # I convert the list symbol to an array, so i can loop through the sub activities. #I need some direction here as how to check whether the symbol will be a skill or activity end 

Hurrah!!

+6
source share
2 answers

Firstly, your yaml file is incorrect YAML, you cannot have such keys, if you have space or weirdness in them, you need to quote them, and what using: in the beginning?

 "Subject_list": "Subject 1": "Act 1": A "Act 2": B "Subject 2": "Skill 1": "Act 1": B "Act 2": B "Skill 2": "Act 1": B 

Then you need to upload the file correctly. You call the load_file method in the YAML module. No :: to access the method in ruby ​​afaik.

 require 'yaml' data = YAML.load_file "file.yaml" subject = data["Subject_list"] require 'pp' subject.each do |s| item = s.last if item.keys.first =~ /Skill/ pp item.keys.inject([]) { |memo,x| item[x].map { |i| memo << i.flatten.unshift(x) } ; memo} else pp item.map { |k,v| ["", k, v] } end end 
+13
source

When creating a YAML file for data, especially a complex data structure, I let YAML generate it for me. Then, if necessary, configure:

 require 'yaml' require 'pp' foo = ["Skill 1","Act 1", "B"], ["","Act 2" "B"],["Skill 2","Act 1", "B"] puts foo.to_yaml 

When I run this code, I get this output:

 --- - - Skill 1 - Act 1 - B - - "" - Act 2B - - Skill 2 - Act 1 - B 

You can prove that the data is correctly generated using YAML generation, then immediately analyze the code and show how it looks like a return structure, allowing you to compare it and check for equality:

 bar = YAML.load(foo.to_yaml) pp bar puts "foo == bar: #{ foo == bar }" 

What will be output:

 [["Skill 1", "Act 1", "B"], ["", "Act 2B"], ["Skill 2", "Act 1", "B"]] foo == bar: true 
+6
source

Source: https://habr.com/ru/post/905594/


All Articles