Saving YAML Data

Another handy way of turning your Ruby objects into YAML format is provided by the dump method. At its simplest, this converts your Ruby data into YAML format and “dumps” it into a string:

yaml_dump1.rb

arr = ["fred", "bert", "mary"]
yaml_arr = YAML.dump( arr )
    # yaml_arr is now: "--- 
- fred
- bert
- mary
"

More usefully, the dump method can take a second argument, which is some kind of IO object, typically a file. You can open a file and dump data to it:

yaml_dump2.rb

f = File.open( 'friends.yml', 'w' )
YAML.dump( ["fred", "bert", "mary"], f )
f.close

Or you can open the file (or some other type of IO object) and pass this into an associated block:

File.open( 'morefriends.yml', 'w' ){ |friendsfile|
    YAML.dump( ["sally", "agnes", "john" ], friendsfile )
}

In each case, the YAML representation of the data from the array will be saved, as plaintext, into the specified file. For example, when the previous code executes, it writes this text into the morefriends.yml file:

morefriends.yml

---
- sally
- agnes
- john

If you use a block, the file will be closed automatically on exiting the block; otherwise, you should explicitly close the file using the close method. You can also use a block in a similar way to open a file and read in YAML data:

File.open( 'morefriends.yml' ){ |f|
    $arr= YAML.load(f)
}

Assuming morefriends.yml contains the data saved earlier, once it is loaded and assigned to the global variable $arr in the block shown earlier, $arr will contain this array of strings:

["sally", "agnes", "john"]
..................Content has been hidden....................

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