I would like to merge arrays in YAML, and load them via ruby -
some_stuff: &some_stuff
- a
- b
- c
combined_stuff:
<<: *some_stuff
- d
-
This post assumes the following context:
lfender6445 wishes to merge two or more lists within a YAML file, and have those merged lists appear as one singular list when parsed.
This may be obtained simply by assigning YAML anchors to mappings, where the desired lists appear as child elements of the mappings. There are caveats to this, however, (see "Pitfalls" infra).
In the example below we have three mappings (list_one, list_two, list_three
) and three anchors
and aliases that refer to these mappings where appropriate.
When the YAML file is loaded in the program we get the list we want, but it may require a little modification after load (see pitfalls below).
list_one: &id001 - a - b - c list_two: &id002 - e - f - g list_three: &id003 - h - i - j list_combined: - *id001 - *id002 - *id003
## list_combined [ [ "a", "b", "c" ], [ "e", "f", "g" ], [ "h", "i", "j" ] ]
This approach allows creation of merged lists by use of the alias and anchor feature of YAML.
Although the output result is a nested list of lists, this can be easily transformed using the flatten
method.
flatten
methodflatten
;; Merge/flatten an array of arraysflatten
;; http://ruby-doc.org/core-2.2.2/Array.html#method-i-flattenflatten
;; https://softwareengineering.stackexchange.com/a/254676/23884