Tj Superfly wrote:
Hello!
I've created a program that will run and update the array storing the
information within that program. When the program is over, I would like
the file to save, so th next time I run it, the same information is in
the array and it will be able to start back where it left off; if that
makes sense.
You can't. You have to save the data to a file and then read the data
back from the file. One approach would be to write each item in the
array to a file. Then, the next time your program runs, you could read
each item back in from the file and insert it in an array. However,
each item you read back will be a string, so if the original item was a
number, you have to convert to the string back to a number. That's kind
of a hassle to do all that.
The ruby standard library yaml will do that all for you. It allows you
to write the whole array to the file and then read the whole array back
in one shot.
One problem you are going to encounter is what to do when you run the
program the first time. You can either create the file beforehand and
leave it blank, e.g.
$touch my_array.yaml #creates a blank file
and then do this:
arr = YAML.load_file("my_array.yaml")
if !arr
arr =
end
Or, you can have your program create the file if it doesn't exist,
something like this:
require 'yaml'
begin
arr = YAML.load_file("my_array.yaml")
rescue Errno::ENOENT #error type is from the error message
#when you open a file that doesn't
exit
#The first time the program is run you will
#get an error saying the file doesn't exist
#which will make execution jump into here.
#By putting this rescue block here,
#the error won't cause your program to
#terminate.
end
if !arr #then the file didn't exist
arr =
end
p arr
#Your program then adds items to arr, e.g.:
arr << 10 << 12.5 << "hello"
#At end of program, write array to file:
File.open("my_array.yaml", "w") do |file|
YAML.dump(arr, file)
end
If you run that a few times, you will see that the data keeps getting
added to the array.
···
--
Posted via http://www.ruby-forum.com/\.