From: Quintus Date: 2011-01-26T22:55:20+09:00 Subject: Re: writing on yaml file Am 26.01.2011 05:00, schrieb Jeremy Bopp: > On 01/25/2011 07:09 PM, Kamarulnizam Rahim wrote: >> Hi guys, >> >> Is it possible for me to write on existing yaml file (i.e add contents >> or change contents) using ruby prgramming? Is there any parser available >> out there? > > The standard library defines the YAML class which can parse and emit > YAML documents. There are quite a few examples out there. I tried a > couple from here that seemed to work: > > http://yaml4r.sourceforge.net/doc/page/examples.htm > > Some code to get you started: > > require 'yaml' > # Load the file. > yaml = YAML.load_stream(File.open('myfile.yaml')) > # Add a new key-value pair to the root of the first document. > yaml.documents[0]['new_key'] = 'new_value' > File.open('myfile.yaml', 'w') do |file| > file.write(yaml.emit) > end > > The above code assumes that you have a valid YAML file in myfile.yaml. > the first document in that file must have key-value pairs at the root. > > -Jeremy > > You can use the YAML module more or less the same way as Marshal, therefore the following is a bit easier I suppose. It parses the whole YAML file and converts it into an appropriate data structure (most likely a hash) with which you can work. Then call YAML.dump with the modified object and the file where you want to save it in. ------------------------------------------------- √ quintus@hades => ~ $ cat test.yml --- a: 5 b: abcdef √ quintus@hades => ~ $ irb irb(main):001:0> require "yaml" => true irb(main):002:0> hsh = YAML.load_file("test.yml") => {"a"=>5, "b"=>"abcdef"} irb(main):003:0> hsh["c"] = 12345 => 12345 irb(main):004:0> File.open("test.yml", "w"){|f| YAML.dump(hsh, f)} => # irb(main):005:0> exit √ quintus@hades => ~ $ cat test.yml --- a: 5 b: abcdef c: 12345 √ quintus@hades => ~ $ ------------------------------------------------- Vale, Marvin