YAML

What is YAML? To know what YAML is, you have to see it for yourself. Or you could see a movie about it. Or I could just tell you.

YAML is a format for representing objects as strings. You can use other formats, but YAML is nice because it’s human-readable (and human-editable) as well as computer-readable. My wife actually writes YAML all the time, right there in her text editor. Then another program reads it in later. Pretty cool.

YAML is not actually part of the Ruby core (it is its own thing, and many other languages can use YAML), but it is part of the standard distribution. What does that mean? Well, when you install Ruby, you install YAML, too. But if you want to actually use YAML, you’ll need to import it into your program. This is really easy, though, with the require method.

require ​'yaml'​ ​# Told you it was easy.
test_array = [​'Give Quiche A Chance'​,
'Mutants Out!'​,
'Chameleonic Life-Forms, No Thanks'​]
# Here's half of the magic:
test_string = test_array.to_yaml
# You see? Kind of like "to_s", and it is in fact a string,
# but it's a YAML description of "test_array".
filename = ​'RimmerTShirts.txt'
File.open filename, ​'w'​ ​do​ |f|
f.write test_string
end
read_string = File.read filename
# And the other half of the magic:
read_array = YAML::load read_string
puts(read_string == test_string)
puts(read_array == test_array )
true
true

Simple. Just two extra lines of code (well, three if you count the require line at the top). So, I’m sure the question burning in all of our hearts is “What does the YAML string look like?!” Run it yourself, and you’ll see this in RimmerTShirts.txt:

---
- Give Quiche A Chance
- Mutants Out!
- Chameleonic Life-Forms, No Thanks

Pretty clear.

Wait a second…I said we were saving and loading only one string. But that file has four lines in it. What, one may be well-justified in asking, gives?

Well, it is one string. It’s a four-line string. How does a string get to have four lines? It has three newline characters. You can add newline characters to strings by just hitting Enter in your code and continuing your string on the next line, though that doesn’t play well with proper indentation and ends up looking ugly. There are somewhat less ugly ways of dealing with it, but they require a different way of defining strings. When we want to make a string, we enclose some text in single quotes, and viola! A string. But there are other ways—like, five other ways—to define strings. I don’t even know what they all are.

To learn them all, there are great references out there (I’ll point them out in Chapter 15, Beyond This Fine Book), but in the meantime, let’s just learn one more that is commonly used….

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.236.191