代码未返回正确答案。
我已经为动物的选择赋予了价值。我把它放在def里面了。
puts "Choose your favorite: cats or dogs"
choose = gets
cats = 1
dogs = 2
def favorite_animal (number)
remainder_when_divided_by_2 = number % 2
if remainder_when_divided_by_2 == 0
return "Ken does too."
end
if remainder_when_divided_by_2 == 1
return "Dogs are better!"
end
end
如果用户输入Cats,答案为“ Ken也这样做!”应该显示。如果用户输入Dogs,则回答“ Dogs更好!”应该显示。我得到的只是1或2个答案。
答案 0 :(得分:2)
尝试一下。
loop do
puts "Choose your favorite: cats or dogs"
case gets.chomp
when "cats"
break "Ken does too."
when "dogs"
break "Dogs are better!"
else
puts "That answer is invalid. Try again"
end
end
这是使用此代码的会话的示例,我的回答是“猪”和“狗”。
Choose your favorite: cats or dogs
pigs
That answer is invalid. Try again
Choose your favorite: cats or dogs
dogs
#=> "Dogs are better!"
请参见Kernel#loop。对于大多数循环,许多Rubyist都将loop
与关键字break
一起使用,而不是while
或until
。 (从未使用过for
循环)。
对于您正在做的事情,您不需要一种方法,但是如果您想添加一条线,那么
def favorite_animal
开头和一行
end
最后。然后
favorite_animal
#=> "Dogs are better!"
前提是我要提供与之前相同的答案。
答案 1 :(得分:1)
发生了几件事:
favorite_animal
;您只定义了它favorite_animal
方法之前,您需要一些逻辑来将输入内容转换为数字puts
或其他方法进行显示)进行处理这是一个可行的最小示例,可能对您了解上述3个问题
def favorite_animal (number)
remainder_when_divided_by_2 = number % 2
if remainder_when_divided_by_2 == 0
return "Ken does too."
end
if remainder_when_divided_by_2 == 1
return "Dogs are better!"
end
end
puts "Choose your favorite: cats or dogs"
choose = gets.chomp
answer = if choose == 'cats'
1
else
2
end
puts favorite_animal(answer)