Building a Deck of Cards in Ruby

I would like to share this challenge I did while at The Firehose Project online bootcamp. The challenge: Build a deck of cards, shuffle them, and deal a card.

The code

Thought process

First, we need to build a class Card  and a method that puts out the name of the card. A card has a rank and a suit. So far this is pretty easy.

Then, we need to build a class Deck  and a method to deal the cards. A deck has 52 cards, can be shuffled, and the dealer can deal one or more cards from the deck. So, we just have to loop through 52 ranks, pair each rank with 4 suits and produce a shuffled deck of cards? Ahhh!

Step 1: create the deck

@ranks stores all the ranks in an array. *(2..10)  is a shortcut using the splat operator which in this case, lists the numbers from 2 to 10. Because it’s done inside the array, it separates and indexes each number.

@suits stores the four suits in an array. I used the symbols, but you could use the first letter of the suit or write the full name out.

@cards is an empty array that will store our newly created deck of cards.

Step 2: loop through the ranks and suits and create 52 cards

Here is what this method of nested loops does:


@ranks = [2, 3, 4, 5] (1st loop)
@suits = [C, H, S, D] (2nd loop)
@cards = [2C]

@ranks = [2, 3, 4, 5] (1st loop)
@suits = [C, H, S, D] (2nd loop)
@cards = [2C, 2H]

@ranks = [2, 3, 4, 5] (1st loop)
@suits = [C, H, S, D] (2nd loop)
@cards = [2C, 2H, 2S]

@ranks = [2, 3, 4, 5] (1st loop)
@suits = [C, H, S, D] (2nd loop)
@cards = [2C, 2H, 2S, 2D]

1st loop takes the 1st element 2 and then the 2nd loop kicks in.
2nd loop takes the 2 and it’s own 1st element C and stores it as a new card into the @cards array.
Here’s the magic: the 2nd loop has to finish before the 1st loop can continue. This results in @cards storing the 1st element of the 1st loop with each element of the 2nd loop until that 2nd loop finishes. Then it repeats with the 2nd element of the 1st loop being stored with each element of the 2nd loop, and so on. How cool is that??

Once the method finishes we now have a full deck of cards stored in our @cards array. We then call .shuffle! method which shuffles the elements in @cards and permanently keeps them that way, since we used the ! operator.

Step 3: deal a card(s)

Since we give this method an argument (number), we can deal as many cards as we want by calling the .times  method. So if we pass the number 7 then 7.times  will do the method’s action … wait for it … 7 times.

We call the .shift  method which removes the first element from our shuffled @cards array (or many elements depending upon what number is passed to the deal method).

Finally we call our .output_card  method that puts  out our card(s)!

(Visited 54 times, 1 visits today)