@hand
如果卡与给定的输入具有相同的等级,我想从阵列中删除卡。我在遍历整个阵列,为什么它没有摆脱最后一张卡?任何帮助是极大的赞赏!
输出:
2 of Clubs
2 of Spades
2 of Hearts
2 of Diamonds
3 of Clubs
3 of Spades
------------
2 of Clubs
2 of Spades
2 of Hearts
2 of Diamonds
3 of Spades
代码:
deck = Deck.new
hand = Hand.new(deck.deal, deck.deal, deck.deal, deck.deal, deck.deal, deck.deal)
puts hand.to_s
hand.remove_cards("3")
puts "------------"
puts hand.to_s
手课:
class Hand
def initialize(*cards)
@hand = cards
end
def remove_cards(value)
@hand.each_with_index do |hand_card, i|
if hand_card.rank == value
@hand.delete_at(i)
end
end
end
def to_s
output = ""
@hand.each do |card|
output += card.to_s + "\n"
end
return output
end
end
卡类:
class Card
attr_reader :rank, :suit
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def to_s
"#{@rank} of #{@suit}"
end
end
remove_cards(value)
有一个问题:delete
在迭代期间不应该这样做。正确的方法是Array#reject!
用手抓牌:
def remove_cards(value)
@hands.reject! { |hand_card| hand_card.rank == value }
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句