有没有"而......其他"在Ruby?

时间:2012-09-16 19:27:27

标签: ruby

我有一个带有cat名称的哈希值和值的cat实例。有没有办法让人们输入一个response,而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 问题或输入:“试试再次”?我想我要求的是“while ... else”。

{{1}}

4 个答案:

答案 0 :(得分: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

这将反复提示用户输入cat名称,直到用户以空字符串响应,此时它将跳出循环。

答案 1 :(得分: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

答案 2 :(得分: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返回“否”,则退出。

答案 3 :(得分: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