【发布时间】:2016-12-19 16:43:48
【问题描述】:
如果卡片与给定输入具有相同的等级,我想从 @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
【问题讨论】:
-
Deck类未显示,您显示的代码未使用Card类。