Back to Our Regularly Scheduled Programming

Now where were we? Ah, yes, YAML. As I was saying, YAML takes (or returns) a multiline string. Go ahead and play around with your YAML code. Get familiar with it. Toss in some arrays within arrays; try to fool it with the integer 42 as opposed to the string '42' or with the true object as opposed to the string 'true'. YAML is pretty smart and, if I may be so bold, darned convenient.

You know what would be even better, though? It would be cool if I could just save an object with one method call, just one line of code. And it’d be cool if I could load with just one method call, too. Check it, yo!

require ​'yaml'
# First we define these fancy methods...
def​ yaml_save object, filename
File.open filename, ​'w'​ ​do​ |f|
f.write(object.to_yaml)
end
end
def​ yaml_load filename
yaml_string = File.read filename
YAML::load yaml_string
end
# ...and now we use these fancy methods.
test_array = [​'Slick Shoes'​,
'Bully Blinders'​,
'Pinchers of Peril'​]
# Hey, time for some "me" trivia:
# In Portland once, I met the guy who
# played Troy's dad. True story.
filename = ​'DatasGadgets.txt'
# We save it...
yaml_save test_array, filename
# We load it...
read_array = yaml_load filename
# We weep for the po' fools that ain't got it...
puts(read_array == test_array)
true

Who’s your daddy? Or at the very least an acquaintance of his? Or maybe just knows that you have a daddy? That’s right, baby, it’s me.

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

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