最后一个元素未在循环中删除

时间:2016-08-12 15:44:40

标签: arrays ruby methods

如果卡与给定输入的排名相同,我想从@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

2 个答案:

答案 0 :(得分:1)

remove_cards(value)有一个问题:在迭代期间不应该delete。正确的方法是手上的Array#reject!张卡片:

def remove_cards(value)
  @hands.reject! { |hand_card| hand_card.rank == value }
end

答案 1 :(得分:0)

您的问题就在这一行

    @hands.each_with_index do |hand_card, i|

您有一个实例变量@hand,而不是@hands