d_zero d_zero - 6 months ago 14
Ruby Question

How to check if any elements of an array are not included in another array?

I'm making a player vs computer Mastermind (the board game) program as part of learning Ruby.

If you don't know Mastermind, basically it's a two-player game where one player creates a code of four colours (i.e. "red red blue yellow") and the opponent tries to guess that code.

The game initializes with a set of available colours and an empty code:

@@colours = ["RED", "BLUE", "YELLOW", "GREEN", "ORANGE", "WHITE"]
@code = []


I can ask the user to set a code like this:

puts "Please set your code:"
code = gets.chomp.downcase.split("")
@code << code


The user inputs the code like so:
rgby
=>
code = ["RED", "GREEN", "BLUE", "YELLOW"]
.

(There will be a method which changes, i.e. "r" to "RED", please assume that happens somewhere in my program.)

I want to make sure the player can only use colours included in
@@colours
, i.e.
pxgb
would not work.

Pseudo-code would be along the lines of:


If all input colours are found in
@@colours
, update
@code
.


or conversely


If any input colours are not found in
@@colours
, do not update
@code
(and possibly do something else).


How do I write this? I'm not too familiar with error handling so I was trying to do it with out but I'm willing to learn if that's the best way to go.

Answer

You could do the following to check if code has only elements from @@colours

(code - @@colours).empty?

Above expression will be true if code contains only elements from @@colours, else it will be false.


PS: In the code sample in question, code is once shown as containing input from gets and another time shown as an array of processed inputs. In the above solution, I am assuming code = ["RED", "GREEN", "BLUE", "YELLOW"]

Comments