Ruby 了解it之外的attr#U reader实例变量可访问性';s起源子类

Ruby 了解it之外的attr#U reader实例变量可访问性';s起源子类,ruby,Ruby,我正在研究一位有良好基础的RubyList,我很难理解如何访问存储在子类组的实例var@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.

我正在研究一位有良好基础的RubyList,我很难理解如何访问存储在子类组的实例var@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
  end
end

two_decks = PlayingCard::Deck.new(2)
puts two_decks
# => #<PlayingCard::Deck:0x007fb5c2961e80>
class播放卡
套装=%w{梅花钻石红桃黑桃}
等级=%w{2 3 4 5 6 7 8 9 10 J Q K A}
甲板
属性读取器:卡片
def初始化(n=1)
@卡片=[]
适合。循环(n)do | s|
等级。循环(1)do | r|
@纸牌#
这很有意义,它从PlayingCard::Deck返回两个_组的对象id。为了使它更有用,我能想到的访问@cards中存储的数组的唯一方法是添加另一个方法Deck#show。现在我可以在@cards上调用其他方法,就像我开始做的那样。这个简单的例子可以得到@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
class播放卡
套装=%w{梅花钻石红桃黑桃}
等级=%w{2 3 4 5 6 7 8 9 10 J Q K A}
甲板
属性读取器:卡片
def初始化(n=1)
@卡片=[]
适合。循环(n)do | s|
等级。循环(1)do | r|
@卡片104

我感到困惑,因为我认为attr_读取器允许@cards实例变量在类外可见。Cards#show方法是否增加了变量的范围?有没有更好的方法让我错过?我是否不知道@cards的操作/信息收集应该在哪里进行?谢谢

在Ruby中,通常不能更改变量的作用域以在其类之外查看它。公开变量的正确方法是将其包装在方法中,就像使用

def show
  @cards
end
attr\u reader
方法是一种方便的方法,可以自动为您创建该方法。因此,添加
attr\u reader:cards
会将此方法隐式添加到类中:

def cards
  @cards
end
这意味着您现在可以使用
two_deck.cards
访问@cards,并且您根本不需要
show
方法

值得一提的是,您还可以使用
attr\u writer:cards
添加此方法:

def cards= value
  @cards = value
end
可以这样称呼:
two_cards.cards=some_value


您可以使用
attr\u accessor:cards
自动添加读写方法。

这就是我想要的。我想我的困惑在于没有意识到attr_*属性可以像方法一样调用。谢谢你的帮助

class播放卡
套装=%w{梅花钻石红桃黑桃}
等级=%w{2 3 4 5 6 7 8 9 10 J Q K A}
甲板
属性读取器:卡片
def初始化(n=1)
@卡片=[]
适合。循环(n)do | s|
等级。循环(1)do | r|

@cards
@cards
是一个实例变量,
attr\u reader
允许您访问(读取)此实例变量的值,您已经在
show
方法中成功地完成了此操作。您仍然感到困惑吗?你明白安德烈的话了吗?谢谢。起初我认为它在PlayingCard类之外是可用的。有没有更合适的方法让我访问@cards表示的数组?除了在PlayingCard::Deck.new实例上创建/调用show方法之外?