Defining struct in a class

W

William Song

How can I properly define a struct in a class?

If I have

class Cards
Card = Struct.new:)suit, :number)
@cardsOnHand=[]

@cardsOnHand.push(Card.new("S","5"))
end

This will give me an error message saying the push is not defined for
NilClass. How should I fix this?
 
W

William Song

Rein said:
The error you reported has nothing to do with your Card struct. Besides
which, your code works for me as is.

Sorry, I meant to put it into a function. I over-simplified it when
posted here.

class Cards
Card = Struct.new:)suit, :number)
@cardsOnHand=[]

def a()
@cardsOnHand.push(Card.new("S","5"))
end
end

cards = Cards.new
cards.a()

The above code will give an error.
 
A

Angus Hammond

I assume you want the first two lines of you class definition to be run
every time someone creates an instance of you class. If you do you
should put the into a method called initialize. That will be run
automatically when new is called and should solve your problem

Rein said:
The error you reported has nothing to do with your Card struct. Besides
which, your code works for me as is.
Sorry, I meant to put it into a function. I over-simplified it when
posted here.

class Cards
Card = Struct.new:)suit, :number)
@cardsOnHand=[]

def a()
@cardsOnHand.push(Card.new("S","5"))
end
end

cards = Cards.new
cards.a()

The above code will give an error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top