Frage

My source code:

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

Whenever I use add option and add something it works. But once I exit and re-open the program, it doesn't show books that I've added using the add option, it returns to the default list. I need Ruby to save all the changes permanently.

War es hilfreich?

Lösung

You have to save your objects yourself, e.g. using YAML:

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

The contents of "data.yml" will be:

---
:Harry_Potter: 5
:Steve_Jobs: 10

To read the file use:

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

Andere Tipps

Well, you could use Maglev which is a ruby interpreter based on the GemStone/S Object Server which will be able to store your books persistently (by setting a reference to your books Hash and Maglev.commit_transaction). However this might be a bit of an overkill for your purposes :-)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top