我有一个 json 文件。我用它来存储信息,因此它会不断地被读取和写入。
总的来说,我对 ruby 和 oop 完全陌生,所以我确信我会以一种疯狂的方式来解决这个问题。
class Load
def initialize(save_name)
puts "loading " + save_name
@data = JSON.parse(IO.read( $user_library + save_name ))
@subject = @data["subject"]
@id = @data["id"]
@save_name = @data["save_name"]
@listA = @data["listA"] # is an array containing dictionaries
@listB = @data["listB"] # is an array containing dictionaries
end
attr_reader :data, :subject, :id, :save_name, :listA, :listB
end
example = Load.new("test.json")
puts example.id
=> 937489327389749
所以我现在可以轻松读取 json 文件,但我怎么能写回文件 - 参考示例?说我想更改 id example.id.change(7129371289)
...或将字典添加到列表 A 和 B ...这可能吗?
- - - - - - - 更新 - - - - - - -
我已经让它工作了,但我相信它会冒犯人们......所以我把它包括在下面。
class Load
def initialize(save_name)
puts "debug printed from inside 'Load'"
puts "loading " + save_name
@data = JSON.parse(IO.read( $user_library + save_name ))
@subject = @data["subject"]
@id = @data["id"]
@is_a = @data["is_a"]
@save_name = @data["save_name"]
@listA = @data["listA"]
@listB = @data["listB"]
def append(dataID, input)
puts "debug printed from inside 'Load' 'append'"
puts dataID
puts input
if dataID == "ListA"
puts "yes this is ListA"
append = @data
append["listA"] << input
puts append
File.open( $user_library + append["save_name"], "w" ) do |f|
f.write(append.to_json)
end
end
if dataID == "ListB"
puts "yes this is ListB"
append = @data
append["listB"] << input
puts append
File.open( $user_library + append["save_name"], "w" ) do |f|
f.write(append.to_json)
end
end
end
end
attr_reader :data, :subject, :id, :save_name, :listA, :listB
end
puts "OPENING SAVED SUBJECT"
puts Load.new("animals.json").listA
puts "CALLING APPEND"
new_hash = {"cow" => "horse"}
Load.new("animals.json").append("ListA", new_hash )