我在學習The Well Grounded Rubyist,並且我無法理解如何訪問存儲在子類Deck的實例var @ card中的數組。瞭解attr_reader實例變量在其源的子類外的可訪問性
class PlayingCard
SUITS = %w{ clubs diamonds hearts spades }
RANKS = %w{ 2 3 4 5 6 7 8 9 10 J Q K A }
class Deck
attr_reader :cards
def initialize(n=1)
@cards = []
SUITS.cycle(n) do |s|
RANKS.cycle(1) do |r|
@cards << "#{r} of #{s}"
end
end
end
end
end
two_decks = PlayingCard::Deck.new(2)
puts two_decks
# => #<PlayingCard::Deck:0x007fb5c2961e80>
這是有道理的,它返回從遊戲牌two_decks ::甲板對象ID。爲了使這個更有用,我想出來訪問存儲在@cards中的數組的唯一方法是添加另一個方法Deck#show。現在我可以打電話給@卡片上的其他方法,就像我準備要做的那樣。這個簡單的例子可以得到@cards的計數:
class PlayingCard
SUITS = %w{ clubs diamonds hearts spades }
RANKS = %w{ 2 3 4 5 6 7 8 9 10 J Q K A }
class Deck
attr_reader :cards
def initialize(n=1)
@cards = []
SUITS.cycle(n) do |s|
RANKS.cycle(1) do |r|
@cards << "#{r} of #{s}"
end
end
end
def show
@cards
end
end
end
two_decks = PlayingCard::Deck.new(2).show
p two_decks.count
# => 104
我很困惑,我認爲attr_reader被允許@cards實例VAR給類以外的可以看出。 Cards#show方法是否會增加變量的範圍?有沒有更好的方法,我失蹤了?我是否應該從@cards收集操縱/信息收集?謝謝!
'@ cards'是一個實例變量,什麼'attr_reader'做是允許你訪問(讀取的值),這個實例變量,你已經在'show'成功完成方法。 –
你還困惑嗎?你瞭解安德烈的評論嗎? –
我的確謝謝。起初我以爲它可以在PlayCard類之外使用。 –