Clarifications on YAML syntax and Ruby parsing
parsing, ruby, yaml
Solution
Case 1: YAML allows unquoted scalars, or "bare" strings not enclosed in quotes. Compared to quoted strings they are less flexible, since you can't use certain characters without creating ambiguous syntax, but the Ruby parser does support them.
1.9.3-p448 > YAML::parse('test').to_ruby
=> "test"
Case 2: As you've guessed, this is Ruby-specific since YAML has no concept of "symbols". When converting a YAML mapping to a Ruby hash, scalar keys that start with a colon are interpreted as symbols instead of strings.
Case 3: Under YAML's definition of a mapping, keys must be unique, so a strict parser should throw an error when given your example. It seems the Ruby parser is more lenient, and allows the same key to be defined multiple times with a last-value-wins rule. This is also allowed in native Ruby hashes.
1.9.3-p448 > YAML::parse("test: true\ntest: false").to_ruby
=> {"test"=>false}
1.9.3-p448 > { 'test' => true, 'test' => false }
=> {"test"=>false}
Problem
I am new to YAML and Ruby. I am using the following Ruby code to parse a YAML file: ``` obj = YAML::load_file('test.yml') ``` Are the following YAML file contents for 'test.yml' valid? Case 1: ``` test ``` In this case, I don't specify the value of `test` (something like `test : true`) but my Ruby parsing code does not throw an error. I thought this was an invalid YAML syntax. Case 2: ``` :test : true ``` In this case, the Ruby code treats `test` as a symbol instead of a string and when I do `puts obj[:test]`, it returns the result to be "true". Is this a Ruby thing? Other languages will interpret it as a string `":test"`? Case 3: ``` :test : true :test : false ``` In this case, instead of throwing up an error for redefinition of `:test`, my Ruby code takes the latest value for `:test` (which is `false`). Why is this? Does YAML syntax allow for re-definition of elements and in which case only the latest value gets taken?