Saving with yaml

Hi,

I have a question. :slight_smile: I have already found a lot in the web but that
does not really helped me. This far my code looks like this:

to save:

require “yaml”

@characters = [“Molly”, “Trade”]
@saves = {location: “Southeaster”,
hunger: 10,
life: 76
}
@settings = {display: “1360*960”,
render: “high”,
saves: “manual”
}

output = File.new(“Saves.yaml”, “w”) do |file|
YAML.dump
end
output.write YAML.dump(@characters) # Wie sichert man mehrere
Sachen???
output.close

and to load:

require “yaml”

output = File.new(“Saves.yaml”, “r”)
p YAML.load(output.read)
output.close

How can I save multiple array etc.?

It works but I want to save more than one hash, I want to save e.g. all
of them, but with that I can save just one or if I manage it to save all
three I can just load the first one.
So it would be nice if someone could help me. :slight_smile: Thanks

Yours faithfully
Greeneco

P.S.
I am sorry, but I did not know how I can post my code not in textform
and had no time to look up because of bad time managment. Sorry

On 8/6/13 5:41 PM, Green E. wrote:

@characters = [“Molly”, “Trade”]
YAML.dump
end
output.write YAML.dump(@characters) # Wie sichert man mehrere

For example:
File.open(“Saves.yaml”, “w”) do |file|
file.write(YAML.dump(@characters))
file.write(YAML.dump(@saves))
file.write(YAML.dump(@settings))
end

or

File.open(“Saves.yaml”, “w”) do |file|
[@characters,@saves,@settings].each do |item|
file.write(YAML.dump(item))
end
end

or even better:

File.open(“Saves.yaml”, “w”) do |file|
file.write(YAML.dump([@characters,@saves,@settings]))
end
YAML.load File.read “Saves.yaml”

=> [[“Molly”, “Trade”], {:location=>“Southeaster”, :hunger=>10,

:life=>76}, {:display=>“1360*960”, :render=>“high”, :saves=>“manual”}]

On Tue, Aug 6, 2013 at 10:41 AM, Green E. [email protected] wrote:

@characters = [“Molly”, “Trade”]
YAML.dump
output = File.new(“Saves.yaml”, “r”)
Yours faithfully
Greeneco


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


ruby-talk mailing list
[email protected]
http://lists.ruby-lang.org/cgi-bin/mailman/listinfo/ruby-talk

I’d probably just put them all in the same hash:

require “yaml”

filename = “data.yaml”
characters = [“Molly”, “Trade”]
saves = {location: “Southeaster”, hunger: 10, life: 76}
settings = {display: “1360*960”, render: “high”, saves: “manual”}
program_data = {characters: characters, saves: saves, settings:
settings}

File.write may not be in some older versions of Ruby

File.write filename, YAML.dump(program_data)

loaded_data = YAML.load(File.read filename)

require ‘pp’
pp loaded_data

>> {:characters=>[“Molly”, “Trade”],

>> :saves=>{:location=>“Southeaster”, :hunger=>10, :life=>76},

>> :settings=>{:display=>“1360*960”, :render=>“high”,

:saves=>“manual”}}

Thank you guys, you really helped me out. Thanks :slight_smile: