Saving hashes to file on Ruby

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

提交回复
热议问题