Reputation: 347
So I have an empty array and a .yml file. I have managed to output the results of that file with this code
puts YAML.load_file('some_yml_file.yml').inspect
I was wondering, how can I pull out each of the data and store them into an empty array?
Is it
emptyarray = []
YAML.load_file('some_yml_file.yml').inspect do |entry|
emptyarray << entry
end
Any help would be appreciated! Thanks!
Upvotes: 0
Views: 788
Reputation: 106087
YAML.load_file
returns a Ruby object corresponding to the type of data structure the YAML represents. If the YAML contains a sequence, YAML.load_file
will return a Ruby array. You don't need to do anything further to put the data into an array, because it's already an array:
yaml = <<END
---
- I am
- a YAML
- sequence
END
data = YAML.load(yaml)
puts data.class
# => Array
puts data == ["I am", "a YAML", "sequence"]
# => true
(You'll notice that I used YAML.load
to load the data from a string rather than a file, but the result is the same as using YAML.load_file
on a file with the same contents.)
If the top-level structure in the YAML is not a sequence (e.g. if it's a mapping, analogous to a Ruby hash), then you will have to do additional work to turn it into an array, but we can't tell you what that code would look like without seeing your YAML.
Upvotes: 1
Reputation: 2302
Change YAML.load_file('some_yml_file.yml').inspect do |entry|
with YAML.load_file('some_yml_file.yml').each do |entry|
and it should work as you expect it (assuming it's not a string).
If you post a sample of your data structure inside the YAML file and what you wish to extract and put in an array then that would help.
Upvotes: 0