我的方法使用可变长度的参数列表,我希望使用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