You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中JSON读写游戏数据时Date转String类型错误如何修复?

错误原因分析

报错no implicit conversion of Date into String的核心问题:

  • 在load_games方法中,你提前将JSON里的publish_date解析成了Date对象,传给Game.new后
  • Game的构造函数调用父类Item的构造函数时,把这个Date对象传了进去
  • 而Item类的构造函数(items.rb第8行)期望接收字符串类型的日期,尝试对Date对象执行Date.parse操作,触发类型转换错误

修复方案

1. 修正game_module.rb

调整load_games方法

不要提前解析日期为Date对象,直接传递字符串给Game构造函数:

require 'json'
require_relative '../classes/game'
require 'date'

def load_games
    data = []
    file = './json_files/games.json'
    if File.exist?(file)
      JSON.parse(File.read(file)).each do |game|
        # 直接传递JSON中的字符串日期,不提前转Date
        data.push(Game.new(
          game['publish_date'], 
          game['multiplayer'], 
          game['last_played_date'], 
          archived: game['archived']
        ))
      end
    else
      # 初始化空数组的正确JSON格式
      File.write('./json_files/games.json', '[]')
    end
  
    data
end  

def create_game
    data = []
    @games.each do |game|
      # 将Date对象转为字符串,并用哈希结构保证JSON格式正确
      data.push({
        publish_date: game.publish_date.to_s,
        multiplayer: game.multiplayer,
        last_played_date: game.last_played_date.to_s,
        archived: game.archived
      })
    end
    File.write('./json_files/games.json', JSON.generate(data))
end

2. 修正game.rb构造函数

确保传给父类Item的日期格式符合要求(假设Item期望接收Date对象,这里统一解析字符串后传递):

require_relative './items'
require 'date'

class Game < Item
  attr_accessor :multiplayer, :last_played_date

  def initialize(date_str, multiplayer, last_played_date_str, archived: false, id: nil)
    # 解析字符串为Date对象后传给父类
    publish_date = Date.parse(date_str)
    super(id, publish_date, archived: archived)
    @multiplayer = multiplayer
    @last_played_date = Date.parse(last_played_date_str)
  end

  def can_be_archived?
    current_date = Date.today
    super && (current_date.year - @last_played_date.year) > 2
  end
end

补充说明

  • 如果Item类的构造函数原本就期望接收字符串日期,只需移除load_games中的Date.parse调用,Game构造函数直接传递字符串给父类即可
  • create_game中必须将Date对象转为字符串,否则会出现JSON序列化错误;同时用哈希结构存入数组,保证和读取时的JSON结构一致

内容的提问来源于stack exchange,提问作者Shaker Abady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:45:13