1

我有一个哈希值,其中键名是猫名,值是猫名。有没有办法做到这一点,当人们键入response不在cats哈希键中的 a 时,终端可以重新打印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返回“否”,则退出。

于 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 回答