开发者

Iterate over Playing Cards array and verify suits

开发者 https://www.devze.com 2023-03-02 05:51 出处:网络
I\'m working with an array that looks like this: cards = [#<Cardshark::Card:0x9200cc @rank=:ace, @suit=:coins>, etc]

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开发者_如何学C 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消