Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving hashes to file on Ruby

Tags:

file

ruby

hash

save

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 question: How could I save/load the hashes with the movies titles and ratings in a file instead of the own code?

Here is how the code looks like right now (a few sentences in Portuguese, but you may just ignore it:

    movies = {
    Memento: 3,
    Primer: 4,
    Ishtar: 1
    }

    puts "O que você gostaria de fazer?"
    puts "-- Digite 'add' para adicionar um filme."
    puts "-- Digite 'update' para atualizar um filme."
    puts "-- Digite 'display' para mostrar todos os filmes."
    puts "-- Digite 'delete' para deletar um filme."

    choice = gets.chomp.downcase
    case choice
    when 'add'
      puts "Que filme você gostaria de adicionar?"
      title = gets.chomp
      if movies[title.to_sym].nil?
        puts "Qual a nota? (Digite um número de 0 a 4.)"
        rating = gets.chomp
        movies[title.to_sym] = rating.to_i
        puts "#{title} foi adicionado com uma nota de #{rating}."
      else
        puts "Esse filme já existe na lista! Sua nota é #                        {movies[title.to_sym]}."
      end
    when 'update'
      puts "Que filme você gostaria de atualizar?"
      title = gets.chomp
      if movies[title.to_sym].nil?
        puts "Filme não encontrado!"
      else
        puts "Qual é a nova nota? (Digite um número de 0 a 4.)"
        rating = gets.chomp
        movies[title.to_sym] = rating.to_i
        puts "#{title} foi atualizado, sua nova nota é #{rating}."
      end
    when 'display'
      movies.each do |movie, rating|
        puts "#{movie}: #{rating}"
      end
    when 'delete'
      puts "Que filme voce gostaria de deletar?"
      title = gets.chomp
      if movies[title.to_sym].nil?
        puts "Filme não encontrado!"
      else
        movies.delete(title.to_sym)
        puts "#{title} foi deletado."
      end
    else
      puts "Desculpa, não entendo o que você quer."
    end

As you can see, the catalog is included in the hash at the beggining of the code however it does not save the information. How could I make it store everything?

Thank you guys!

like image 409
Wesley Nazeazeno Avatar asked Jun 08 '15 20:06

Wesley Nazeazeno


People also ask

Do Ruby hashes preserve order?

As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.

Are hashes objects in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


1 Answers

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 
like image 173
Nick Veys Avatar answered Oct 16 '22 11:10

Nick Veys