YAML is a very universal format for storing data in a way that can be transferred between applications and programming languages. JSON is another option that is very common on websites.
I use YAML for things like configuration files because it is very easy to read and modify. For example, this Ruby structure:
irb(main):002:0> foo = { 'a' => 1, 'b' => [2, 3], 'c' => { 'd' => 4, 'e' => 5 } } { "a" => 1, "b" => [ [0] 2, [1] 3 ], "c" => { "d" => 4, "e" => 5 } }
It looks like this when converting to YAML:
irb(main):003:0> puts foo.to_yaml --- a: 1 b: - 2 - 3 c: d: 4 e: 5
You can save this in a file:
File.open('foo.yaml', 'w') { |fo| fo.puts foo.to_yaml }
and read it back:
bar = YAML.load_file('foo.yaml') { "a" => 1, "b" => [ [0] 2, [1] 3 ], "c" => { "d" => 4, "e" => 5 } }
Similarly, using JSON:
puts foo.to_json {"a":1,"b":[2,3],"c":{"d":4,"e":5}}
You can save JSON in a file similar to YAML, and then reload it and re-include it in the hash. This is a slightly different syntax:
irb(main):011:0> File.open('foo.json', 'w') { |fo| fo.puts foo.to_json } nil irb(main):012:0> bar = JSON.parse(File.read('foo.json')) { "a" => 1, "b" => [ [0] 2, [1] 3 ], "c" => { "d" => 4, "e" => 5 } }
A big win in any language that can read YAML or JSON can read these files and use the data, either by reading OR, or writing them.
Performing a string replacement is very simple after you have the hash, because Ruby String gsub
understands the hashes. This is from the docs :
If the second argument is a hash, and the matched text is one of its keys, the corresponding value is a replacement string.
This means you can do something like this:
foo = 'Jackdaws love my giant sphinx of quartz' bar = { 'quartz' => 'rosy quartz', 'sphinx' => 'panda' } foo.gsub(Regexp.union(bar.keys), bar) "Jackdaws love my giant panda of rosy quartz"
You need to keep track of the conflicts between the words that perform the wildcard, but the \b
flag in the pattern may help. Doing this work is an exercise for the reader.