将哈希值保存到 Ruby 上的文件 [英] Saving hashes to file on Ruby

查看:29
本文介绍了将哈希值保存到 Ruby 上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在编程中迈出第一步.我刚刚完成了 Code Academy 的另一门课程.这次我被要求创建一个小型电影目录.这是我的问题:如何在文件而不是自己的代码中保存/加载带有电影标题和评级的哈希?

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?

谢谢你们!

推荐答案

如果它们是简单的哈希,YAML 文件可能是一种简单的方法.

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 

这篇关于将哈希值保存到 Ruby 上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆