I have a problem with Object-Oriented Project Hangman - serialization part. I saved my code in serialize method, but when I try to unserialize it, I have a problem with it. I see all components of classes in the YAML file and when I try to reach them with code, I can't do it. I don't know where the problem is. Here is my serialize method and deserialize method.
def serialize
file = File.open('game.yml', 'w') do |f|
YAML.dump(self, f)
end
file.close
exit
end
def deserialize
File.open('game.yml', 'r') do |f|
p YAML.load(f)
end
# p file['word']
end
If you want to see my all codes, here is my GitHub and Repl
Repl : https://replit.com/@Burakkepuc/Hangman#main.rb
GitHub : https://github.com/Burakkepuc/Hangman
CodePudding user response:
I think it's actually working fine.
YAML.load
returns an different instance of Game. You can call methods on that instance, but you don't have any access to the properties.
def deserialize
File.open('game.yml', 'r') do |f|
loaded_game = YAML.load(f)
puts loaded_game.length # fails with method not found
end
# p file['word']
end
add a reader to you Game class and then the above will report the value of the length in the newly load instance of Game.
attr_reader :length
I am not sure what you want to do with the loaded game, but perhaps you simply want to call guess
on it?
def deserialize
File.open('game.yml', 'r') do |f|
loaded_game = YAML.load(f)
loaded_game.guess
end
end