2016-11-03 2 views
3

미리 결정된 해시의 값을 사용자에게 제공하고 응답을 입력으로 가져 오는 간단한 어휘 퀴즈를 작성합니다. 사용자 입력이 값의 해당 키와 일치하면 프로그램은 다음 값으로 이동하고 해시의 모든 키 - 값 쌍이 고려 될 때까지이 프로세스를 반복합니다.해시에서 키 - 값 쌍을 무작위로 배열합니다.

현재 상태에서 퀴즈는 해시 값을 첫 번째부터 마지막까지 순차적으로 사용자에게 묻습니다.

그러나 퀴즈를 더 어렵게 만들기 위해 퀴즈에서 해시의 임의 값을 특별한 순서없이 제공하고 싶습니다.

일반 영어 ... 매번 같은 순서로 동일한 정의를 인쇄하는 대신 라이브러리에서 임의의 정의를 뱉어내는 vocab 퀴즈를 얻으려면 어떻게해야합니까?

내 코드는 다음과 같습니다. 모두의 도움에 진심으로 감사드립니다!

vocab_words = { 
    "class" => "Tell Ruby to make a new type of thing", 
    "object" => "Two meanings: The most basic type of thing, and any instance of some thing", 
    "instance" => "What you get when you tell Ruby to create a class", 
    "def" => "How you define a function inside a class" 
} 

vocab_words.each do |word, definition| 
    print vocab_words[word] + ": " 
    answer = gets.to_s.chomp.downcase 

    while answer != "%s" %word 
     if answer == "help" 
     print "The answer is \"%s.\" Type it here: " %word 
     answer = gets.to_s.chomp.downcase 
     else 
     print "Nope. Try again: " 
     answer = gets.to_s.chomp.downcase 
     end 
    end 
    end 

답변

1

사용 : random_keys = vocab_words.keys.shuffle과 같이 :

vocab_words = { 
    "class" => "Tell Ruby to make a new type of thing", 
    "object" => "Two meanings: The most basic type of thing, and any instance of some thing", 
    "instance" => "What you get when you tell Ruby to create a class", 
    "def" => "How you define a function inside a class" 
} 

random_keys = vocab_words.keys.shuffle 
random_keys.each do |word| 
    print vocab_words[word] + ": " 
    answer = gets.to_s.chomp.downcase 

    if answer == "help" 
    print "The answer is \"%s.\" Type it here: " %word 
    answer = gets.to_s.chomp.downcase 
    else 
    while answer != "%s" %word 
     print "Nope. Try again: " 
     answer = gets.to_s.chomp.downcase 
    end 
    end 
end 
+0

정말 고마워요! 제안을 사용하면 완벽하게 작동합니다. 도움을 감사하십시오. – and1ball0032

관련 문제