Ruby程序不保存哈希变化

时间:2014-04-08 06:25:23

标签: ruby hash save

我的源代码:

books = {
    Harry_Potter: 5,
    Steve_Jobs: 10
}

def finder(bookName)
    books.each {
            |n| if n == bookName
                puts "Are you sure you want to #{choice} #{n}?"
                confirmAction = gets.chomp
                    if confirmAction == "yes" 
                    case choice
                        when "update"
                            puts "Enter the new name:"
                            newName = gets.chomp.to_sym
                            books[newName.to_sym] = books.delete(n)
                            puts "Update the rating for #{newName}:"
                            newRating = gets.chomp.to_i
                            books[newName.to_sym] = newRating.to_i
                            puts "Successfully updated #{newName} with rating of #{newRating}"

                        when "delete"
                            books.delete(n)

                        else puts "Invalid option!"
                    end

                else puts "Invalid book name."
                end
            end

            }
end


puts "What would you like to do?\n[Add] [Update] [Delete] [View]"
action = gets.chomp.capitalize

case action
    when "Add"
        puts "Enter the new book name:"
        title = gets.chomp.to_sym
        puts "Please rate the book [1-10]:"
        rating = gets.chomp.to_i
        books[title.to_sym] = rating.to_i
        puts "Successfully added #{title} with rating of #{rating}"
        puts books

    when "Update"
        choice = "update"
        puts "Enter the name of the book:"
        bookName = gets.chomp.to_sym
        finder(bookName)

    when "Delete"
        choice = "delete"
        puts "Enter the name of the book:"
        bookName = gets.chomp.to_sym
        finder(bookName)

    when "View"
        choice = "view"
        puts books.each {
            |k, v| puts "#{k}: #{v}"
        }
    end

每当我使用添加选项并添加它有效的内容时。但是,一旦我退出并重新打开该程序,它就不会显示我使用添加选项添加的书籍,它会返回默认列表。 我需要Ruby永久保存所有更改。

2 个答案:

答案 0 :(得分:1)

您必须自己保存对象,例如使用YAML

require 'yaml'
File.write('data.yml', YAML.dump(books))

" data.yml"的内容将是:

---
:Harry_Potter: 5
:Steve_Jobs: 10

要阅读文件,请使用:

books = YAML.load(File.read('data.yml'))
#=> {:Harry_Potter=>5, :Steve_Jobs=>10}

答案 1 :(得分:0)

好吧,您可以使用Maglev这是一个基于GemStone/S Object Server的红宝石口译员,可以持久存储您的图书(通过设置对books哈希的引用和{ {1}})。然而,对于您的目的而言,这可能有点过分: - )