Ruby 序列化和反序列化 json

问题描述 投票:0回答:1

我有这两个函数来序列化和反序列化游戏状态。我让它工作正常。但给人的感觉却是非常的混乱和凌乱。有更好的方法吗?

我需要从 Main 类序列化两个不同的类变量,从 Game 类(猜测类的父类)序列化三个变量。从主类调用以下方法:

  def save_game(obj)
    saved_data = {
      score: obj.score,
      secret_word: obj.new_guess.secret_word,
      running_guess: obj.new_guess.running_guess,
      not_in_word: obj.new_guess.not_in_word
    }.to_json
    save_file(saved_data)
  end

  def load_game(obj)
    saved_data = JSON.load_file('saved/saved_game.json')
    obj.score = saved_data['score']
    obj.new_guess.secret_word, = saved_data['secret_word']
    obj.new_guess.running_guess = saved_data['running_guess']
    obj.new_guess.not_in_word = saved_data['not_in_word']
    display_secret_hidden(obj.new_guess.running_guess)
    display_not_included_letters(obj.new_guess.not_in_word)
    play_rounds
  end

我试图理解这个寻找替代解决方案,但到目前为止无法以其他方式做到这一点。

json ruby serialization deserialization
1个回答
0
投票

您缺少数据对象

无论它是 Ruby 的新数据对象之一,还是像妈妈过去制作的老式结构,你最好为某种数据结构传递实例变量,而不是尝试在不同的地方动态序列化每个元素.

无论您是序列化为 JSON、YAML 还是像 Marshal 这样的二进制格式,都有一些方法可以让您的代码更加简洁。 Marshal 和 YAML 在序列化对象方面做得更好; JSON 在这方面有一点限制,除非您采取一些明确的步骤。因此,我将与 Marshal 一起演示如何轻松恢复序列化对象。

以下示例将您的游戏保存包装到具有 @file 和 @save_data 可访问属性的 Games 类中。考虑以下几点:

class Game
  attr_accessor :file, :save_data
  SaveData =
    Struct.new *%i[score secret_word running_guess not_in_word]

  def initialize(filename="game_save.bin", **kwargs)
    @file = filename
    @save_data = SaveData.new
    @save_data.members.map { @save_data[_1] = kwargs[_1] }
  end

  def save
    File.open(@file, ?w) { Marshal.dump @save_data, _1 }
  end

  def load
    @save_data = Marshal.load File.read(file)
  end
end

if __FILE__ == $0
  # create a new game and populate some data.
  game = Game.new score: 1, foo: 2, not_in_word: 3

  # save the game to a file, then clobber the file
  # and display the now-empty Struct.
  game.save
  game.save_data = Game::SaveData.new
  game.save_data

  # load and display the previous save
  game.load
end

使用结构为您提供了一个可以传递的数据对象,它们非常适合此目的。通过将 Struct 对象与全局关键字参数的解构相结合,您可以极大地简化和干燥代码,而不会丢失任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.