'New with ruby. Id and quantity of item

I'm new to ruby, and I'm trying to edit others scripts made in ruby to figure out how it works. Now, I was struggling for days with this one. I have a script with the next command:

def has_card_in_deck?(id)
  actor = $game_actors[$game_variables[27]]
    for card in actor.deck
      return true if card.id == id
    end
  return false
end

This return me if there's a card with the said ID in the actor deck. It works perfectly. But I tried to create a second command with the almost exact question, but instead of return me if there's a card with certain ID, I want to confirm if there's 2 or more copies of that ID card. I can't figure out how to ask the quantity of the object "card". I tried putting (* 2) with the ID, but of course, this will just ask if there's a card with the double value of the id input.



Solution 1:[1]

Use #count in of Array. For example,

nums = [1,2,2,3,4,5]
nums.count { |num| num == 2 }
=> 2
nums.count { |num| num >= 3 }
=> 3

So you can write a has_at_least_2_cards?(id)

def has_at_least_2_cards?(id)
  actor = $game_actors[$game_variables[27]]
  actor.deck.count { |card| card.id == id } >= 2
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kevinluo201