Saving hashes to file on Ruby

前端 未结 3 652
孤街浪徒
孤街浪徒 2020-12-20 21:28

I\'m just giving my first steps in programming. I have just finished another class in Code Academy. This time I was asked to create a small movie catalog. Here is my questio

3条回答
  •  伪装坚强ぢ
    2020-12-20 21:39

    You can simply use JSON, like this

    require 'json'
    
    FILE_PATH = "catalogue.json"
    
    def load
      data = nil
      File.open(FILE_PATH) do |f|
        data = JSON.parse(f.read)
      end
      data
    end
    
    def save(data)
      File.open(FILE_PATH, "w+") do |f|
        f << data.to_json
      end
    end
    
    def process
      catalogue = load
    
      p catalogue
    
      catalogue["Memento"] = 4
      save(catalogue)
    end
    
    process
    # => {"Memento"=>3, "Primer"=>4, "Ishtar"=>1}
    catalogue = load
    
    p catalogue
    # {"Memento"=>4, "Primer"=>4, "Ishtar"=>1}
    

提交回复
热议问题