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:
- Why doesn’t this work the way I’m trying to do it?
- 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
On Fri, May 7, 2010 at 6:49 PM, Leon T. [email protected]
wrote:
I’ve created this simplified version of the code to focus on this
attr_accessor :name, :value
def initialize
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”)
Josh C. wrote:
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")
So basically, my method was working as intended, but I was looking for
the result in the wrong place. Seems like an obvious mistake (name
conflict) to avoid now.
Thank you!