gpt4 book ai didi

ruby - 如何永久更新 Ruby 中的哈希值?

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:50 24 4
gpt4 key购买 nike

所以我在这里看到了关于如何写入外部文本文件等的问题。例如,将我的哈希值写入我放置的另一个文件:

hash = {
Key1: Value1,
Key2: Value2
}
open(FileToWriteTo, 'w') do |f|
hash.each { |key, value| f.puts "#{key}: #{value}" }

但我想要实现的是,如果我运行该程序并将某些内容添加到我的哈希列表中,那么下次我运行并显示该哈希时,新添加的内容就会出现。这是我用来添加到哈希中的代码:

puts "Type 'add' to add an item to the hash"

choice = gets.chomp.downcase

case choice
when 'add'
puts "What do you want to add?"
addition = gets.chomp
if hash[addition.to_sym].nil?
puts "What value will #{addition} have? (integer)"
add_value = gets.chomp
hash[addition.to_sym] = add_value.to_i
puts "#{addition} has been added with a value of #{value}."
else
puts "That item already exists! Its value is #{hash[addition.to_sym]}."
end

所以如果我添加项目,重新运行程序并选择显示而不是添加,我应该如何让最后添加的显示。谢谢。

最佳答案

这是您可以使用的代码。它利用 yaml 来存储哈希。

require 'yaml'

file = '/tmp/test.yml'
if File.exists?(file)
hash = YAML::load_file(file) # load yaml
else
hash = Hash.new
end

puts "Type 'add' to add an item to the hash"
choice = gets.chomp.downcase

if choice == 'add'
puts "What do you want to add?"
addition = gets.chomp
if hash[addition.to_sym].nil?
puts "What value will #{addition} have? (integer)"
add_value = gets.chomp
hash[addition.to_sym] = add_value.to_i
puts "#{addition} has been added with a value of #{add_value}."
else
puts "That item already exists! Its value is # {hash[addition.to_sym]}."
end
end

File.open(file, 'w') {|f| f.write hash.to_yaml } #store yaml

关于ruby - 如何永久更新 Ruby 中的哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35821435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com