Ruby Classes

Time to get classy

12/29/2014

Ruby is a real classy lady. Meaning she is an object-oriented language that deals with classes. Let's look at that in real world terms. Just like in the real world there are objects, each of which are unique. You are a unique person as much as I am. In that situation, we are both objects and Person would be the class. Let's take a look at how we would show that in Ruby.


          1     class Person
          2
          3       def initialize(name, age)
          4         @name = name
          5         @age = age
          6         @species = "Homo Sapien"
          7       end
          8
          9       def hello
          10        puts "Hello! My name is #{@name}."
          11      end
          12  
          13      def say_age
          14        puts "I am #{@age} years old."
          15      end
          16
          17      def say_species
          18        puts "I am a #{@species}."
          19      end
          20
          21    end
          22
          23    me = Person.new("Zac", 25)
          24    you = Person.new("Someone", 24)
            

Ok, so let's take a look at what is happening here. We start our class with class Person. We then define a method called initialize and we pass in arguments for name and age on line 3. This is a default method that can be used to do something when the object is first created. What is happening with that weird looking @name and @age? These are known as instance variables. They are unique to the object when it is created. What we are doing is setting the instance variables equal to the arguments of the same name. If you look at line 23, you can see where the object me will have a @name of "Zac" and a @age of 25.

Starting on line 9 and continuing on to line 19, we see three methods. These methods are unique to the Person class and can be called by any of its objects. Let's try to use one of these methods.


                me.hello
                me.say_age

                "Hello! My name is Zac."
                "I am 24 years old."
            
What we can see here is because me is an object of the Person class, it is able to use all the methods that Person has. This is super useful when you want to create a method in one place but use it over and over again on objects of the same class.