Saving hashes to file on Ruby

前端 未结 3 650
孤街浪徒
孤街浪徒 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:34

    If they're simple hashes, a YAML file may be an easy way to do it.

    require 'yaml'
    
    # write hash out as a YAML file
    movies = { Memento: 1, Primer: 4, Ishtar: 1 }
    File.write('movies.yml', movies.to_yaml)
    
    # read back in from file
    from_file = YAML.load_file('movies.yml')
    
    # use it
    from_file[:Memento]
    # => 1 
    from_file[:Primer]
    # => 4 
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-12-20 21:46

    The best way according to me is using Marshal method as explained here Marshaling The Marshal module dumps an object in a string, which can be written to a file. Reading the file and Marshal.Loading the string gives the original object. Writing to a file can be achieved using Marshal.dump

    For example in your code this can be achieved using

    movies = {
    Memento: 3,
    Primer: 4,
    Ishtar: 1
    }
    # dumping:
    File.open("test.marshal", "w"){|to_file| Marshal.dump(movies, to_file)}
    # retrieving:
    p File.open("test.marshal", "r"){|from_file| Marshal.load(from_file)}
    #gives you movies = {Memento: 3,Primer: 4,Ishtar: 1}
    

    Another method is explained by @Nick Veys using Yaml it is also used by people a lot.

    Similar explanations can be obtained here as well.Closest match I found

    0 讨论(0)
提交回复
热议问题