我正在做TodoList,而 想將列表保存爲JSON文件,但它只保存了Class名稱。將數組中的類轉換爲JSON
下面的代碼:
require 'date'
require 'json'
class TodoList
attr_accessor :title
def initialize(title)
@title=title
@items=[]
end
def rename(title)
@title=title
end
def add_item(new_item, due_date)
item=Item.new(new_item)
item.set_due_date(due_date)
@items.push(item)
end
def save
if json_instance = self.to_json
puts "Saved Successfully"
end
File.open("file_json_complete.json", "w") do |f|
f.write(json_instance)
end
end
end
class Item
attr_reader :complete_status, :description, :due_date, :created_at
def initialize(description)
@description=description
@complete_status=false
@created_at=Date.today
end
end
doh=TodoList.new("doh's stuff")
# Add four new items
doh.add_item("laundry", 10)
doh.add_item("study",20)
doh.add_item("sleep", 15)
doh.add_item("Watch Movie", 5)
doh.save
結果文件中只顯示類名TodoList:0x00000000965e88
。
謝謝。這一個正是我想要的.. –