allan.m.miller / gmail.com wrote:

> Hello,
> 
> I'm new to yaml, and yaml in Ruby.
> 
> I'm trying to create a yaml file in a text editor, one part of which
> will consist of an array of of arrays.  The data structure I'm trying
> to represent is:
> 
> [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
> 
> an array of three arrays.

Or a two-dimensional array.

> I've tried to create this yaml file in a text editor (test.cfg):
> 
> -- a
>  - b
>  - c
> -- d
>  - e
>  - f
> -- g
>  - h
>  - i

Can I ask what guidance you have that this is valid YAML syntax?

> and read it in as follows
> 
> require 'yaml'
> na = open('test.cfg') { |f| YAML.load(f) }
> 
> I get a load error:
> 
> $ ./test.rb
> /usr/lib/ruby/1.8/yaml.rb:119:in `load': parse error on line 9, col -1:
> `' (ArgumentError)
>         from /usr/lib/ruby/1.8/yaml.rb:119:in `load'
>         from ./test.rb:3
>         from ./test.rb:3:in `open'
>         from ./test.rb:3
> 
> The last line seems o be causing an ArgumentError.
> 
> I'm sure my approach is completely off - how does one represent an
> array of arrays in yaml, and load it into a Ruby array of arrays?

We are faced here with a question of how one converts a hand-entered,
plain-text file that we hope is valid YAML, into a Ruby array. How shall we
solve this problem?

Well, we could type a bunch of stuff into a text editor, run it through a
YAML interpreter, and see if it turns into the desired array when parsed.
This could take a long time.

But how about this? Why don't we attack this problem from the other
direction? Why don't we take the original array, convert it into YAML, and
see how it looks?

#!/usr/bin/ruby

require 'yaml'

array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

YAML.dump(array,STDOUT)

Output:

---
- - a
  - b
  - c
- - d
  - e
  - f
- - g
  - h
  - i

Something tells me (even thought I haven't tried it) that, if I take this
YAML output and use it as an input, the original array will be recreated.

One more question. Why are you trying to create YAML data by hand? True,
YAML data is human-readable, but that doesn't guarantee that it's
human-writable.

Parting shot. Confucius say, "avoid data formats in which whitespace is
syntactically significant."

-- 
Paul Lutus
http://www.arachnoid.com