這是一個相當知名的方法。確定撲克牌的等級。我創建了以下類:Card
:從另一個類中的方法調用方法
class Card
attr_accessor :suite, :rank, :value
def initialize(suite, rank, value)
@suite = suite
@rank = rank
@value = value
end
def to_s
puts "#{@value}, #{@suite}, #{@rank}"
end
end
Deck
:
class Deck
def initialize()
@cardsInDeck = 52
@deck = Array.new()
end
def add_card(card)
@deck.push(card)
end
def deck_size
@deck.length
end
def to_s
@deck.each do |card|
"#{card.rank}, #{card.suite}"
end
end
def shuffle_cards
@deck.shuffle!
end
def deal_cards
#Here I create a new hand object, and when popping cards from the deck
# stack I insert the card into the hand. However, when I want to print
# the cards added to the hand I get the following error:
# : undefined method `each' for #<Hand:0x007fa51c02fd50> (NoMethodError)from
# driver.rb:36:in `<main>'
@hand = Hand.new
for i in 0..51 do
card = @deck.pop
@cardsInDeck -= 1
puts "#{card.value}, #{card.rank}, #{card.suite}"
@hand.add_cards(card)
end
@hand.each do |index|
"#{index.value}, #{index.rank}, #{index.suite}"
end
puts "Cards In Deck: #{@cardsInDeck}"
end
end
Hand
require_relative 'deck'
require_relative 'card'
class Hand
def initialize()
@hand = Array.new()
end
def to_s
count = 0
@hand.each do |card|
"#{card.value}, #{card.rank}, #{card.suite}"
count += 1
end
end
def add_cards(card)
@hand.push(card)
end
def hand_size()
@hand.length
end
end
和驅動程序文件:
require 'logger'
require_relative 'card'
require_relative 'deck'
require_relative 'hand'
suite = ["Hearts", "Diamonds", "Clubs", "Spades"]
rank = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
deck = Deck.new()
suite.each do |i|
v = 1
rank.each do |j|
deck.add_card(Card.new(i, j, v))
v += 1
end
end
在Deck
類中,deal_card
方法,我不理解爲什麼循環用於陣列引起的方法錯誤
@hand.each do |index|
"#{index.value}, #{index.rank}, #{index.suite}"
end
puts "Cards In Deck: #{@cardsInDeck}"
謝謝,這很有道理。我不清楚我如何循環在手牌類中定義的甲板類中的陣列,以便列出所有已添加到甲板類中的手牌。 – user2872898
您需要在'Hand'中定義'each'方法或者將'Hand'定義爲提供這種方法的類的子類(例如'Array')。 –
歡迎使用堆棧溢出。 :-)如果您覺得這篇文章不能令人滿意地回答您的問題,請隨時留下您的問題以獲取更多回復。否則,你可能想要「接受」它。 –