From: w_a_x_man Date: 2010-11-29T12:30:18+09:00 Subject: Re: Loading variables from a file [Noob Question] On Nov 28, 11:44 am, Richard Mccormack wrote: > Hey everyone, > I've been working on some sort of a test-based game to learn ruby (and > programming in general :) and I got stuck with my saving/loading system. > To show you what I mean, this is what I used to save the game. (I want > the code to be as modular as I can, I have some sort of an addon system > planned...) > > def savegame(name, varstosave) >   savegame = File.new(name + ".tsl", "w") >      savegame.puts varstosave.to_s >      while varstosave.length != 0 >         savegame.puts varstosave[0] >         savegame.puts eval(varstosave[0]).to_s >         varstosave.delete_at(0) >      end >   savegame.close > end > > So, now I am trying to to load the variables from the file. I came up > with the start of a function: > > def loadgame(name, varstoload) >   puts "Loading..." >   loadgame = File.open(name + ".tsl", "r") >     while varstoload.length != 0 >         # ? >     end >   loadgame.close > end > > Where varstoload/varstosave is an array. Problem with the loading is > that I assumed there  was a way to take the first variable name from the > array and actually use it as a variable. So, if the array is > ["$intellect", "$strength"], I thought I would be able somehow to turn > a[0] into a variable object. It seems that there isn't a way to do this, > so I was wondering if there was a better way to manage the > saving/loading. Use a hash (associative array). def save_game( name, hash ) open( name + ".tsl", "w" ){|f| f.puts hash.to_a.join( "\n" ) } end def load_game( name ) hash = {} open( name + ".tsl", "r" ){|f| while key = f.gets hash[ key.strip ] = f.gets.to_i end } hash end status = {} status[ 'intellect' ] = 140 status[ 'strength' ] = 120 save_game( 'foo', status ) p load_game( 'foo' )