如何将if-else语句与可变长度的参数列表一起使用



我的方法使用可变长度的参数列表,我希望使用if-else语句检查每个变量。这可能吗?我不确定我的语法是否正确。

def buy_choice(*choice)
loop do
input = gets.chomp
if input == choice
puts "You purchased #{choice}."
break
else
puts "Input '#{input}' was not a valid choice."
end
end
end

因此,如果我使用buy_choice("sailboat", "motorboat"),则"sailboat""motorboat"input应该是成功的。

使用数组#include?查找对象是否在列表中

def buy_choice(*choices)
loop do
print 'Enter what did you buy:'
input = gets.chomp
if choices.include? input
puts "You purchased #{input}."
break
else
puts "Input '#{input}' was not a valid choice."
end
end
end
buy_choice 'abc', 'def'
Enter what did you buy:abc1
Input 'abc1' was not a valid choice.
Enter what did you buy:def1
Input 'def1' was not a valid choice.
Enter what did you buy:abc
You purchased abc.
=> nil 

相关内容

  • 没有找到相关文章

最新更新