【问题标题】:storing user input to an empty hash将用户输入存储到空哈希
【发布时间】:2014-06-17 17:33:21
【问题描述】:

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

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

...程序继续

稍后我想让用户输入“评论”以将其(以及输入的任何其他内容)显示为信息:

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

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

【问题讨论】:

  • 但是您没有在hash 中添加任何值,并且您正在尝试调用哈希......太棒了! -1
  • 你一直隐藏在 ... 行中的内容...程序继续.. 清楚地问你问题.. 我们不会猜测..
  • 这就是我要问的......我不想调用空哈希。如何将这些变量“存储”在哈希中,使其不为空?
  • 如果用户跑两次相同的距离会发生什么?
  • 没关系,我只想要一个总列表

标签: ruby save hash


【解决方案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 中的所有可用方法。

【讨论】:

  • 感谢@cereal 真正回答了我的问题。
【解决方案2】:

在编写您的程序时,如果用户两次(不同的时间)跑了相同的距离,则只会记录 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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多