Using Array as Super Class Question

I think a Deck of cards can be modeled by an Array. So let’s say I do this:

class Deck < Array
    def initialize
        super (1..52).to_a
    end
end

The problem I am having is this. I really like to use the inherited “generator methods”. e.g.:

d = Deck.new
d.shuffle!
d.class --> this gives Deck... awesome

However, this loses the “Deck” class:

e = d.shuffle
d.class --> this gives Array

How can I make all the inherited Array generator methods cast the results back to Deck? (that is without typing out each of the methods in the Deck class… that seems to defeat the purpose of inheritance).

This also seems like a less than optimized method… offloading the task to the caller:

e = Deck.new(d.shuffle)

Thanks

You’ll have to create a shuffle method in Deck which returns a Deck. Are you sure a Deck ‘is a’ Array? Maybe its better to think of a Deck as having an(has a) array of Cards. If you choose the latter then you can create a Card class which will contain a trump and value.

If I was creating a Deck of Cards, I would start with something like:

require 'inum'

class Suit < Inum::Base

    define :SPADE
    define :HEART
    define :CLUB
    define :DIAMOND

end

class Value < Inum::Base

    define :ACE, 1
    define :TWO, 2
    define :THREE, 3
    define :FOUR, 4
    define :FIVE, 5
    define :SIX, 6
    define :SEVEN, 7
    define :EIGHT, 8
    define :NINE, 9
    define :TEN, 10
    define :JACK, 11
    define :QUEEN, 12
    define :KING, 13

end

class Cards

    def initialize
        @cards = []
        Suit.each{|s| Value.each{|v| @cards.push([s, v].freeze)}}
        
    end

    def cards

        @cards

    end

end

class Deck

    def initialize

        @cards = Cards.new

    end

    def shuffle!

        @cards.cards.shuffle!
        self

    end

    def display_deck

        @cards.cards.each{|c| puts "#{c[0]} #{c[1]}"}

    end

end

if __FILE__ == $0

    myDeck = Deck.new

    myDeck.shuffle!.display_deck

    puts "\n\n"

    yourDeck = Deck.new

    yourDeck.display_deck

end


All good suggestions. Thanks.