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

问题描述 投票:0回答:1

我的方法使用可变长度的参数列表,我想使用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"),则input"sailboat""motorboat"应该成功。

ruby methods variable-length
1个回答
2
投票

使用Array#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 
© www.soinside.com 2019 - 2024. All rights reserved.