2017-02-13 14 views
0

我在學習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收集操縱/信息收集?謝謝!

+0

'@ cards'是一個實例變量,什麼'attr_reader'做是允許你訪問(讀取的值),這個實例變量,你已經在'show'成功完成方法。 –

+0

你還困惑嗎?你瞭解安德烈的評論嗎? –

+0

我的確謝謝。起初我以爲它可以在PlayCard類之外使用。 –

回答

0

在Ruby中,您通常無法將變量的範圍更改爲在其類外查看。揭露一個變量的正確方法是將其包裝在一個方法像你

def show 
    @cards 
end 

attr_reader方法是自動爲您創建的方法的簡便方法一樣。所以加入attr_reader :cards隱式添加這個方法到類:

def cards 
    @cards 
end 

這意味着你現在可以訪問使用two_decks.cards @cards,你不需要show方法都沒有。

這可能是值得一提的是,你還可以使用attr_writer :cards添加這個方法:

def cards= value 
    @cards = value 
end 

可以稱之爲像這樣:two_cards.cards = some_value

你也可以使用attr_accessor :cards自動添加這兩種讀和寫入方法。

0

這就是我想要的。我認爲我的困惑並沒有意識到attr_ *屬性可以被稱爲一種方法。謝謝您的幫助!

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) 
 
p two_decks.cards.count