1

キーの猫の名前と値の猫のインスタンスを持つハッシュがあります。人々がハッシュresponseのキーにない a を入力したときcatsに、端末がputs "Which cat would you like to know about?"質問を再印刷するか、「もう一度やり直してください」と入力するようにする方法はありますか? 私は一種の「しばらくの間...他に」を求めていると思います。

puts "Which cat would you like to know about?"
puts cats.keys
response = gets.chomp

while cats.include?(response)
  puts "The cat you chose is #{cats[response].age} old"
  puts "The cat you chose is named #{cats[response].name}"
  puts "The cat you chose is a #{cats[response].breed} cat"
  puts "Is there another cat would you like to know about?"
  response = gets.chomp
end
4

4 に答える 4

2

私の知る限り、「while...else」はありません。応答が有効な猫の名前であるかどうかに関係なく、ループが継続することを気にしない場合は、おそらくこれでうまくいくでしょう:

puts "Which cat would you like to know about?"
puts cats.keys

while true
  response = gets.chomp
  if response.empty?
    break
  elsif cats.include?(response)
    puts "The cat you chose is #{cats[response].age} old"
    puts "The cat you chose is named #{cats[response].name}"
    puts "The cat you chose is a #{cats[response].breed} cat"
    puts "Is there another cat would you like to know about?"
  else
    puts "There is no cat with that name. Try again."
  end
end

これにより、ユーザーが空の文字列で応答するまで繰り返し猫の名前を入力するよう求められます。空の文字列が返された時点で、ループから抜け出します。

于 2012-09-16T19:38:47.897 に答える
0

追加の質問でコードを再配置できます。

cats = {'a' => 1} #testdata
continue = true   #set a flag

while continue
  puts "Which cat would you like to know about?"
  response = gets.chomp
  while cats.include?(response)
    puts cats[response]
    puts "Is there another cat would you like to know about?"
    response = gets.chomp
  end
  puts "Try another? (Y for yes)"
  continue = gets.chomp =~ /[YyJj]/ #Test for Yes or yes, J for German J...
end
于 2012-09-16T19:42:59.950 に答える
0

Rubyで遊んでからしばらく経ちますが、次のようなことが思い浮かびます。

def main
   print_header
       while true
           resp = get_response
           if cats.include?(resp)
              print_info(resp)
           else
              print_header
       end
end

def get_response
    puts cats.keys
    response = gets.chomp
end

def print_header
    puts "Which cat would you like to know about?"
end

def print_info response
  puts "The cat you chose is #{cats[response].age} old"
  puts "The cat you chose is named #{cats[response].name}"
  puts "The cat you chose is a #{cats[response].breed} cat"
  puts "Is there another cat would you like to know about?"
end

終点が必要になりますのでご注意ください。get_response「no」を返した場合は、終了します。

于 2012-09-16T19:43:42.460 に答える
0
continuous = false
loop do
  unless continuous
    puts "Which cat would you like to know about?", cats.keys
  else
    puts "Is there another cat would you like to know about?"
  end
  if cat = cats[gets.chomp]
    puts "The cat you chose is #{cat.age} old"
    puts "The cat you chose is named #{cat.name}"
    puts "The cat you chose is a #{cat.breed} cat"
    continuous = true
  else
    continuous = false
  end
end
于 2012-09-16T20:15:19.817 に答える