使用 Hash 中的 Key Value 对作为问答

Using Key Value pairs in Hash as question and answer

我正在编写我的代码训练营的作业,它涉及 ruby。

创建一个包含国家和首都哈希值的程序,如下所示:

cos_n_caps = {
    "USA" => "Washington, DC", 
    "Canada"=>"Ottawa",  
    "United Kingdom"=>"London",
    "France"=>"Paris", 
    "Germany"=>"Berlin", 
    "Egypt"=>"Cairo", 
    "Ghana"=>"Accra", 
    "Kenya"=>"Nairobi", 
    "Somalia"=>"Mogadishu", 
    "Sudan"=>"Khartoum", 
    "Tunisia"=>"Tunis",
    "Japan"=>"Tokyo", 
    "China"=>"Beijing",
    "Thailand"=>"Bangkok", 
    "India"=>"New Delhi", 
    "Philippines"=>"Manila", 
    "Australia"=>"Canberra", 
    "Kyrgyzstan"=>"Bishkek"
}

向用户询问每个国家的首都,并告诉他们是否正确。另外,记录分数并在测验结束时给他们打分。

我想知道我是否可以通过某种方式循环键列表并在每个键之后请求 user_input 然后再次检查值。

我尝试过使用hash.for_each{|key| puts key},但我不知道如何在按键之间请求user_input

这就是我要做的,除非我能找到更简单的方法:

s = "What is the capital of"
score = 0
count = 0

until count == 1
    puts "#{s} USA"
    a = gets.chomp.downcase
    if a == c["USA"].downcase
        puts "Congrats"
        score += 1
        count += 1
    else 
        puts "nope" 
        count +=1
    end
end

使用 Hash#each to loop through each pair of countries and capitals. In that loop, use Kernel#gets to read their answer and String#chomp 删除他们答案中的换行符。

cos_n_caps.each do |country,capital|
  puts "What is the capital of #{country}?"
  answer = gets.chomp

  if capital.downcase == answer.downcase
    puts "Right!"
  else
    puts "Sorry, it's #{capital}."
  end
end