How do I remove a setting from a YAML file?

I’m working on a small command line app project at the moment and I need
to store settings. I decided to use YAML for the first time and a hash,
which is converted into a string which is in YAML, and then save that
into a file. The below is the code for the writing to the file:

read
previous_settings = @result
@settings.each do |k, v|
previous_settings[k] = v
end
if File.writable_real?(FILE)
File.open(FILE, ‘w+’) do |f|
f << previous_settings.to_yaml
end
@result = true
else
@result = false
end

All it does is it reads the file and sets its contents to the @result
variable. Then the previous_setting variable is set to that and the
contents of the @settings are added onto it. I then simply write to the
file. My question is: how do I delete a setting in a YAML file? Say this
is my YAML file:


foundation: http://foundation.zurb.com/files/foundation-4.1.6.zip
normalize: http://necolas.github.io/normalize.css/2.1.1/normalize.css
h5bp: https://github.com/h5bp/html5-boilerplate/archive/master.zip

And I want to remove the h5bp option? Is there a way of doing that
without actually opening the file, searching through it with Regex, and
then removing the setting and its value? I’m using Ruby 2.0.0p0
(2013-02-24 revision 39474) [x86_64-linux].

Thank so much!

Am Sun, 12 May 2013 20:39:37 +0900
schrieb “Rafal C.” [email protected]:

Hi Rafal,

File.open(FILE, ‘w+’) do |f|
f << previous_settings.to_yaml
end

Why do you use “w+” as the file mode? You don’t read from the file in
the supplied block.

My question is: how do I delete a setting in a YAML file?
Say this is my YAML file:


foundation: http://foundation.zurb.com/files/foundation-4.1.6.zip
normalize: http://necolas.github.io/normalize.css/2.1.1/normalize.css
h5bp: https://github.com/h5bp/html5-boilerplate/archive/master.zip

And I want to remove the h5bp option?

Simply load the YAML file, delete the corresponding hash key, and write
the file back out to disk.

hsh = YAML.load_file("yourfile.yml")
hsh.delete("h5bp")
File.open("yourfile.yml", "w"){|f| YAML.dump(hsh, f)}

Vale,
Marvin


Blog: http://pegasus-alpha.eu/blog

ASCII-Ribbon-Kampagne () | ASCII Ribbon Campaign ()

On Sun, May 12, 2013 at 8:36 AM, Rafal C. [email protected] wrote:

Works great, thanks a lot.


Posted via http://www.ruby-forum.com/.

Um, you do know that YAML files are plain, old text files and can be
edited by any text editor, yes?

Works great, thanks a lot.

Um, you do know that YAML files are plain, old text files and can be edited by
any text editor, yes?

Yeah, why are you asking?

On Sun, May 12, 2013 at 3:34 PM, Rafal C. [email protected] wrote:

Yeah, why are you asking?

Because you were asking how to remove a line from a YAML file…

tamouse mailing lists wrote in post #1108699:

On Sun, May 12, 2013 at 3:34 PM, Rafal C. [email protected] wrote:

Yeah, why are you asking?

Because you were asking how to remove a line from a YAML file…

In Ruby, not by hand.