On Fri, May 7, 2010 at 6:49 PM, Leon Theremin <thephist / hotmail.com> wrote:

> First, I've not used a forum before, but I want to be more involved.
> Please excuse (and correct) poor etiquette.
>
> The context for what I'm really trying to do is that I want to make card
> games. I have general purpose classes for "card" objects (Card, Deck,
> Shoe). And I have game specific classes, which may need to modify
> attributes of the card objects. For example, each card has 'suit',
> 'rank', and 'value' - the 'value' of Jack in Black Jack is 10, but in
> solitaire it's 11.
>
> I've created this simplified version of the code to focus on this
> problem.
>
> Problem: Game.cards is the same before and after Game.assign_values (no
> values assigned).
>
> My questions are:
> 1. Why doesn't this work the way I'm trying to do it?
> 2. Should I be using a different approach?
>
> class Card
>  attr_accessor :name, :value
>  def initialize(name)
>    @name = name
>    @value = nil
>  end
> end
>
> class Game
>  attr_accessor :cards
>  NAMES = ['a','b','c','d']
>  NAME_VALUES = { 'a' => 1,'b' => 2,'c' => 3,'d' => 4 }
>  def initialize
>    @cards= self.cards
>  end
>
>  def cards
>    cards = []
>    NAMES.each do |n|
>      card = Card.new(n)
>      cards << card
>    end
>    cards
>  end
>
>  def assign_values
>    @cards.each do |card|
>      name = card.name
>      value = NAME_VALUES[name]
>      card.value = value
>    end
>  end
> end
>
> g = Game.new
> p g.cards
> g.assign_values
> p g.cards
> --
> Posted via http://www.ruby-forum.com/.
>
>
You have an instance method called cards which returns an initialized set of
cards. When you say "p g.cards" at the end, you are calling this method, so
you are simply calling this method, so you are getting the returned value of
Game#cards, the value returned by the cards method that you have defined.
However, your @cards instance variable is initialized when you say
g.assign_values, but that isn't what you are printing out.

To see the difference:

g = Game.new
p g.cards
g.assign_values
p g.cards
p g.instance_variable_get("@cards")