Before creating an example class it is important to understand what an instance of a class is. The example we will use in this post is the class: Dog. An instance of Dog is a " Male, German Shepard that is 7 years old" To clarify " the German Shepard" is a specific instance of the class Dog.
In our example, the instance of Dog is a "German Shepard." There are many instances (or breeds) of a Dogs in the real world (puddle, pug, lab etc..) so we can create instance variables. These variables are used specifically within the class. To add to our example, our Dog which is a "German Shepard" named "Ronald" is a "Male" and "7 years old" Each of these could be the instance variables @breed, @name @sex, @age respectively. We create instance variables with an @ in front and can use them within all methods in the class.
Class Dog
def initialize(breed, name, sex, age)
@breed = breed
@name = name
@sex = sex
@age = age
end
# the method initialize is a special instance method that kicks off automatically the as soon as a new instance is created. So in this example it would define our instance methods.
def bark
puts "Rooooof! Rooooof!"
end
# this is an instance method. We can call this "custom made" method on the instance of Dog. So if our instance was "my_pet", then the calling of the method would look like this: "my_pet.bark"
def show_collar
puts " Hello, my name is #{@name} I am a #{@sex}, #{@breed}. I am #{@age} years old, not that anyone is counting!"
end
# with this instance method we are using the pre-defined instance variable to puts what the collar of our Dog would look like.
end
--
my_pet = Dog.new("German Shepard", "Ronald", "Male", 7)
# here we are actually creating an instance of our Dog. Notice it needs info because of the initialize method.
--
Now we will test out some of our instance methods!
my_pet.bark => "Rooooof! Rooooof!"
my_pet.show_collar => "Hello, my name is Ronald I am a Male , "German Shepard". I am 7 years old, not that anyone is counting!"