Ciaran S Ciaran S - 3 months ago 5
Ruby Question

Last element not being removed in loop

I want to remove the card from the

@hand
array if it has the same rank as the given input. I'm looping through the entire array, why doesn't it get rid of the last card? Any help is greatly appreciated!

Output:

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


Code:

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


Hand class:

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


Card class:

class Card

attr_reader :rank, :suit

def initialize(rank, suit)
@rank = rank
@suit = suit
end

def to_s
"#{@rank} of #{@suit}"
end
end

Answer

remove_cards(value) has an issue: one should not delete during iteration. The correct way would be to Array#reject! cards from a hand:

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