Hey I'm writing a simple game, where I want to save progress and load it at another point. One one the elements to save is an array. I want to save this array in one single line as an array and also load it again as an array, but it only takes the first element and the following elements overwrite further content
Example (wrong) - Save Data
player_1 = "name"
array = [1, 2, 3]
count = 1000
File.open("game.txt", "w+") do |file|
file.puts player_1
file.puts array
file.puts count
end
Example (wrong) - Load Data
file_data = File.open("game.txt").readlines.map(&:chomp)
player_1 = file_data[0]
array = file_data[1]
count = file_data[2]
OUTPUT: TEXTFILE
name
1
2
3
1000
So I converted the array to a string and write it in text-file (it works but seems inconvenient)
to save the array
file.puts double_checker.to_s
# Output: String
"[1, 2, 3]"
to load the array (load string from text file, delete special chars, convert it back to array, convert elements to integers)
# Converts String back to Array, digits convert to Integers
double_checker = double_checker.delete(" []").split(",").map { |s| s.to_i }
# Output: Array
[1, 2, 3]
Now my question: Is there a way to store the array directly into to text file (in one line) and read it the same way, so I can store the array straight into a variable?
Or is it only possible to store Strings into a text file?
I'm trying to figure out how I can use write/read to save and load files for example a game progress.
File.open(andString#chomp):File.readlines("game.txt", chomp: true). This automatically also closes the file immediately.putsdocs: "If called with an array argument, writes each element on a new line." If you wantputsto output the whole array in one line, you have to convert it into a single-line string yourself, maybe viajoin.