From: Robert Klemme Date: 2004-01-27T03:14:55+09:00 Subject: Re: Print empty values to a file? "Qubert" schrieb im Newsbeitrag news:ae5c96cb.0401260829.63d13a13@posting.google.com... > I am in the middle of writing a wrapper to FORTRAN programs using > Ruby. It going great so far. The problem that I need this groups > help to solve follows: > > For the purposes of a reference, a log and to allow continuation of > the script, I have created a function that writes inquired values to a > file, as follows: > > def savevaribles > fs = File.new("./savedvaribles.rb","w") > # Saved variables from harmprocessing.rb > fs.puts "# Saved variables from harmprocessing.rb" > fs.puts "$year = #{$year}" > fs.puts "$gonl = #{$gonl}" > fs.puts "$tm = #{$tm}" > fs.puts "$timezone = #{$timezone}" > fs.close > end A first remark: you should definitely use the block form: File.open("savedvaribles.rb", "w") do |fs| fs.puts "# Saved variables from harmprocessing.rb" # ... end This way you ensure the file is closed properly, regardless how you leave the block. > Which creates a file that I can "load" with all my variables. > # Saved variables from harmprocessing.rb > $gonl = 149.98435 > $tm = 135 > $timezone = -9 > > The list is much more extensive than this and many of the values are > not set until later in the analysis. If the value is not set or if it > is "nil" the commands #{$value} is blank, which is fine except, > $value1 = > $value2 = 42 > Upon reading the file, the value of $value1 is set to 42 also, which > confuses further analyses. > So I am trying to figure out a cleaver means to check if each value > exists or nil then 'puts "nil"' so there are no more blanks. > I can do this the brute force method, with if/then statements > everywhere, but I was wondering if there is a Ruby way to accomplish > this. If you don't need to edit those variables by hand you can marshal them. A convenient way is to use a hash for that # names must be an array of global variable names like ["$foo", "$bar"] def save_vars(names) h = {} # for globals only names.each {|name| h[name]=eval name} save_hash h end def save_hash(hash) File.open("savedvaribles.rb", "wb") do |fs| Marshal.dump( hash, fs ) end end def load_hash File.open("savedvaribles.rb", "rb") do |fs| Marshal.load( fs ) end end def load_vars load_hash.each do |name, val| # note: name contains the name of a global var # val is referenced directly! eval "#{name} = val" end end Something along these lines. robert