Tuesday, March 5, 2013

Yaml Basics and Some Simple Examples (Part 1)

Yaml is a great tool for storing configuration data. Just check out the config folder of your rails app, you will find plenty of files ending with .yml. You can load your yaml file by calling the method YAML.load_file. After a yaml file is loaded into memory, it presents itself as either Array or Hash, which depends on how the original yaml file has been written.

In a yaml file, indentations are not just used for ease of reading, they are actually used to indicate parent node and child node. Here is how yaml's official site (http://www.yaml.org/spec/1.2/spec.html#id2777534) puts it, Each node must be indented further than its parent node. All sibling nodes must use the exact same indentation level. However the content of each sibling node may be further indented independently.

In the following, I will show you four yaml files. Two of them presents themselves as arrays after they are read into memory, and the other two presents themselves as hashes.

test_1.yml
- Abraham Lincoln 
- George W. Bush
- Barack Obama
=> ["Abraham Lincoln", "George W. Bush", "Barack Obama"]

test_2.yml
name: David
age: 25
gender: male 
 => {"name"=>"David", "age"=>25, "gender"=>"male"}

test_3.yml
team_1:
  - Brian
  - David
  - Tom

team_2: 
  - Mike
  - Bob
  - Sam

team_3: 
  - Adam
  - Aron
  - Bruce 
 => {"team_1"=>["Brian", "David", "Tom"], "team_2"=>["Mike", "Bob", "Sam"], "team_3"=>["Adam", "Aron", "Bruce"]}

test_4.yml
-
 name: david
 age: 25
 gender: male
-
 name: sam
 age: 22
 gender: male
-
 name: bill
 age: 29
 gender: male 
=> [{"name"=>"david", "age"=>25, "gender"=>"male"}, {"name"=>"sam", "age"=>22, "gender"=>"male"}, {"name"=>"bill", "age"=>29, "gender"=>"male"}]

We see two symbols here, the dash and space ("- ") and the colon and space (": "). The former is used to mark the start of an array member and the latter is used to mark a key-value pair. So for the four test files, after we load them into memory, we get an array, a hash, a hash whose values are arrays and an array of hashes, respectively.

No comments:

Post a Comment