我正在使用一个看起来像这样的数组:
cards = [#<Cardshark::Card:0x9200cc @rank=:ace, @suit=:coins>, etc]
4张花色(硬币、剑、杯子、梅花)中的每一张都包含7张王牌和3张扑克牌,每“副牌”总共40张。
我希望写一个rspec测试来验证数组是否包含4个套件。我开始在使用正则表达式的块中使用@cards.select
,这很快就变得丑陋起来。
处理这个问题的最好方法是什么?
发布于 2011-04-30 04:31:06
尝试使用Enumerable#group_by:
num_suits = cards.group_by { |card| card.suit }.length
在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
发布于 2011-04-30 04:46:53
describe Cardshark, "@cards" do
it "should contain four suits" do
suits = @cards.map { |card| card.suit }.uniq
suits.size.should be 4
end
end
https://stackoverflow.com/questions/5837056
复制相似问题