0

My method uses a variable length argument list, and I would like to like to check each variable using an if-else statement. Is this possible? I'm unsure if my syntax is correct.

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

So if I use buy_choice("sailboat", "motorboat"), an input of either "sailboat" or "motorboat" should be successful.

Richard
  • 164
  • 7
  • `if choice.include?(input)` – IMP1 Mar 05 '20 at 14:09
  • To clarify, `choice` in your method is an [array](https://www.digitalocean.com/community/tutorials/how-to-work-with-arrays-in-ruby). The [`include?`](https://ruby-doc.org/core-2.5.0/Array.html#method-i-include-3F) method returns true if the input is an element of the array. – IMP1 Mar 05 '20 at 14:11

1 Answers1

2

use Array#include? to find if an object is in the list

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 
kevinluo201
  • 1,444
  • 14
  • 18