Tuesday, 11 February 2014

Ruby - Instance and Class Variables

When we have an instance of any kind of object in Ruby, it will have certain variables that are unique to it. These variables are therefore referred to as Instance variables and they are denoted by the use of the @ sigil. You’ve probably read that in Ruby everything is an object, therefore we’re practically always going to have a collection of instance variables available to call on.



YouTube Channel: [WATCH, RATE, SUBSCRIBE]

Class variables are set-up when we define a Class in our script, they are denoted by the use of the @@ sigil and are common across all instances of the Class.

It’s important to note that we define our Class variables when write up the Class, with the structure we want, at the time we create the script. These will be re-used by all future instances of the Class and will carry the same data into all instances.

The value of individual Instance variables is set when we create an instance of the Class when the script is running. The data / value it holds is unique to the instance and gives it some variation on other Instances.

Let’s look at an example which shows @instance and @@class variables being used.

Copy the following code into a new .rb file, then run it via a cmd window.

# instanceAndClassVariables_001.rb
# Define a Class called Creature and set a Class variable with @@
class Creature
  @@mobType = "NPC"

def initialize  creatureName
    @name = creatureName
  end #def initialize creatureName

  def to_s
    "Creature name is #{@name}. It is an #{@@mobType}."
  end # def to_s
 
end #Creature class

# Create a new instance of the Creature class, then assign it a name via the @name Instance variable
mob_001 = Creature.new "Silver Kobold"

# View the details of the Class, calling the Class and Instance variables
print mob_001



In this example of a simple Class, we see both Instance and Class variables being used. Our Class variable is @@mobType and this example it’s an “NPC” (a Non-Player Character). We can tell that all instances of this Creature class will be the NPC mob type. However, the particular name of this instance of the creature isn’t set until we create an instance of it.

YouTube Channel: [WATCH, RATE, SUBSCRIBE]
or

0 comments: