访问ruby实例变量的最佳实践



David Black的"基础良好的Rubister"提供了一个示例来说明cycle方法的使用:

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
deck = PlayingCard::Deck.new

我想访问在一个子类中定义的实例变量@cards。访问此数组的最佳方法是什么?

我的理解是,我必须在Deck中添加一个实例方法。有更好的技术吗?

分配牌的最佳方式是什么?

您现在已经可以访问它了,因为您的脚本调用attr_reader :cards:

my_deck = PlayingCard::Deck.new(10)
my_deck.cards

attr_reader是一个"类宏"(Paolo Perrotta在他的《元编程Ruby》一书中提到了这种模式),它只是将getter定义为同名的ivar:

# this line...
attr_reader :cards
# ... is equivalent to 
def cards
  @cards
end

现在,如果你真的想要的话,你可以刺穿对象的面纱,用instance_variable_get:直接访问它的实例变量

my_deck.instance_variable_get(:@cards)

但是,如果可能的话,尽量避免这种情况,以保持对象的良好封装。

最新更新