Caley Woods
Caley Woods

Reputation: 4737

Iterate over Playing Cards array and verify suits

I'm working with an array that looks like this:

cards = [#<Cardshark::Card:0x9200cc @rank=:ace, @suit=:coins>, etc]

Each of 4 suits (coins, swords, cups, clubs) contains ranks ace through seven and 3 face cards for a total of 40 cards per "deck"

I am looking to write an rspec test to verify that the array contains 4 suits. I started going down the path of using @cards.select with a block using regular expressions and that got ugly pretty fast.

What's the best way to handle this?

Upvotes: 0

Views: 307

Answers (2)

Bashwork
Bashwork

Reputation: 1619

describe Cardshark, "@cards" do
  it "should contain four suits" do
    suits = @cards.map { |card| card.suit }.uniq
    suits.size.should be 4
  end
end

Upvotes: 2

robbrit
robbrit

Reputation: 17960

Try using Enumerable#group_by:

num_suits = cards.group_by { |card| card.suit }.length

In IRB:

~$ irb
>> groups = (1..10).group_by { |n| n % 4 }
=> {0=>[4, 8], 1=>[1, 5, 9], 2=>[2, 6, 10], 3=>[3, 7]}
>> groups.length
=> 4

Upvotes: 2

Related Questions