From: Josh Cheek Date: 2012-01-29T14:22:31+09:00 Subject: Re: Class variables --f46d0444ee733706cd04b7a3e9a7 Content-Type: text/plain; charset=ISO-8859-1 On Sat, Jan 28, 2012 at 8:11 PM, josh j. wrote: > Hey guys, > > I'm a newbie to programming and Ruby. I'm just learning about Classes > and wondering about instance variables inside classes. > > I'm in the process of making a trading card game and I have a class > called FieldController. Now each player has at least two fields so I > have a total of 4 different instances? of this class. > For example: > class FieldController > @@space1 = [] > @@space2 = [] > @@space3 = [] > @@space4 = [] > @@space5 = [] > def addcard(para) > ... > end > def removecard > def list > etc > end > > Problem: Having them as class variables doesn't work when there is > multiple FieldControllers... Instance variables don't seem to work > because I can't access them from within the methods such as addcard. > Normal variables are the same. > Questions: > 1. How do I create variables that are specific to that particular > instance of FieldController and can be accessed inside the methods. > Use instance variables, not class variables. class FieldController def initialize @space1 = [] @space2 = [] @space3 = [] @space4 = [] @space5 = [] end def addcard(para) end end Now, your numbering of variables is unusual. It might be better to have a variable, @spaces which contains a five element array. > 2. How can I access the variables from within an object without making a > method as an interface, such as: > $field1 = FieldController.new > puts $field1.space1 > > Variables are not directly exposed, there must always be a method that sets / gets the value. Your example, however, is how things currently work, so maybe I don't understand? (as an aside, when you create a variable with a $dollar_sign, it becomes globally visible, so make sure this is _really_ what you want -- if it is, it likely shouldn't be). class FieldController # define the getter def space1 @space1 end # define the setter def space1=(new_space) @space1 = new_space end def initialize # invoke the setter self.space1 = 'space one' end end # `field1` is a local variable, `$field1` would be global field1 = FieldController.new puts field1.space1 # >> space one --f46d0444ee733706cd04b7a3e9a7--