将用户输入存储到空哈希

时间:2014-06-17 17:33:21

标签: ruby save hash

我正在写一个基本程序。我开始使用空哈希,并使用gets.chomp并希望将信息存储到哈希中,以便稍后可以调用它(在同一个会话中)。

runs = {}
puts "how many miles did you run?"
miles = gets.chomp
puts "how long did it take you?"
time = gets.chomp

...程序继续

稍后我想让用户输入'review'来显示此信息(以及输入的任何其他信息)作为信息:

runs.each do |miles, time|
   puts "#{miles} miles in #{time} minutes."
end

我知道我在“gets.chomp”之前/之后遗漏了一些东西。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

要将键值对添加到哈希,您可以使用runs[miles] = time

所以你的代码看起来像这样:

runs = {}
puts "How many miles did you run?"
miles = gets.chomp
puts "How long did it take you?"
time = gets.chomp

runs[miles] = time

# When user enters `review`
runs.each do |miles, time|
    p "#{miles} miles in #{times} minutes."
end

这不是向哈希添加键/值对的唯一方法,因此您可以查看rubydoc中可用的所有方法。

答案 1 :(得分:0)

在编写程序时,如果用户运行相同的距离两次(使用不同的时间),则仅记录 last 结果,因为哈希不能存储重复的键。更好的方法是将它存储在元组数组中(==具有两个值的数组):

runs = []

puts "How many miles did you run?"
miles = gets.chomp
puts "How long did it take you?"
time = gets.chomp
runs << [miles, time]

# ...    

runs.each do |miles, time|
   puts "#{miles} miles in #{time} minutes."
end

答案 2 :(得分:0)

runs = Hash.new
puts "How many miles did you run?"
runs ["miles"] = gets.chomp
puts "How long did it take you?"
runs ["time"] = gets.chomp

# When user enters `review`
runs.each do |miles, time|
    p "#{miles} miles in #{times} minutes."
end