Ruby Programming Tutorial - Lesson 18 - Classes and Objects in Ruby :)

in #ruby7 years ago (edited)

ruby.jpg

Instance Variables

Boring Definition

An instance variable has a name beginning with @ , and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables.

Simple Definition

Variable whose name starts with an @ symbol is called an instance variable :)

@student, @bilal-haider are all instance variables ...
Lets take a look at this Student Class ..
That helps us create new students with few properties.
Each and every student must have an ID, a name and an address. these are 3 properties of our Students :)
We can add more but for the sake of simplicity, we have only three.

  • student id
  • name
  • address

Every Class which you create, should have an initialize method, or its also called constructor method.
which is a special method, because it gets called whenever a new object is created from class ..

Here is how you create a Class,

It begins with the keyword "Class" after keyword we choose a name for it..
and it ends with the keyword "end"
In the body of class you have Methods, and methods contain ruby instructions


class Student
   def initialize(id, name, addr)
      @student_id = id
      @student_name = name
      @student_addr = addr
   end
   def display_details()
      puts "Student id #@student_id"
      puts "Student name #@student_name"
      puts "Student address #@student_addr"
   end
end

# Create Objects
student1 = Student.new("1", "Bilal", "Islamabad, Pakistan")
student2 = Student.new("2", "BagoSan", "Belgium, Belgium")

# Call Methods
student1.display_details()
student2.display_details()

Here, @student_id, @student_name and @student_addr are instance variables. 
This will produce the following result −

Student id 1
Student name Bilal
Student address Islamabad, Pakistan
Student id 2
Student name BagoSan
Student address Belgium, Belgium

Note that, we created a student1 object, using the "Student.new" which calls constructor method, or initialize Method and initializes the properties for us. Properties that we are passing as arguments to initialize method.

student1 = Student.new("1", "Bilal", "Islamabad, Pakistan")

Second Method is a regular method. Which we can use like so .
student1.display_details()

Also keep in mind that, we cannot call methods of objects.. before we create them..

we cannot do something like this,
bilal.display_details()
.. it will throw us error.. because bilal is not an object of Student Class.. hence it does not have access to the methods..

before calling any methods on objects.. we need to create an object.. that we do so, by using

bilal = Student.new("3", "Bilal", "Mars")
now that object "bilal" is created from "Student class", we can now call methods which
this object has..

it currently has only one object method .. so we can call it :)
bilal.display_details()

Lets Create Humans :) with as many properties as we want ..

You are thinking, Bilal is going crazy ?? can we create Humans in ruby :p
well not humans but Records of humans probably ...

Screenshot from 2018-03-11 21-31-22.png

In order to Create as many Humans, with as many properties ... we need to have a class,
From that Class we can create as many objects as we want..
Each new object with different properties.. In the following Example we are going to make a ruby Program
that exactly does that..

Note we are using many skills in this example, that we have learned in previous articles.
We will recap the skills we used at the end of this article..

### Create a Human being Whose name is Bilal Haider
### Who is cute, lovely and can program Ruby 

### defining Class .. which will alow us to create as many Humans as we want. 
class Human
    ## constructor function which takes variable length of parameters 
    def initialize(*properties)

        ## Empty Array Where we can store all the arguments which we receive in *properties
        @human_qualities = []

        ## Looping through properties and storing each property in instance Array
        properties.each do |property|

            ## which is equivalent to @human_qualities.push(property)
            @human_qualities << property
        end
    end
    ## Creating Method that displays first property 
    ## which we assume to be the name of Human 
    def display_name
        puts "This Human is #{@human_qualities[0]}"
    end

    def is_cute
        puts "#{@human_qualities[0]} is #{@human_qualities[1]}"
    end

    def is_lovely
        puts "#{@human_qualities[0]} is #{@human_qualities[2]}"
    end

    def is_programmer
        puts "#{@human_qualities[0]} is a #{@human_qualities[3]}"
    end

end
## Finally Creating a Human, whose name is Bilal Haider, and He is Cute, Lovely and is a programmer :)
new_human = Human.new("Bilal Haider", "Cute", "Lovely", "Programmer")
new_human.display_name
new_human.is_cute
new_human.is_lovely
new_human.is_programmer

You can open the image in your browser, if Quality is not good.

Screenshot from 2018-03-11 16-07-31.png

In this article We Learned Following Things

  • Learned that instance Variables Start with @ symbol ..

  • Learned that if we create a Class we can create Many objects from that Class
    - e.g We Created Human Class, and we can Create as many Humans as we want
    - example: human1 = Human.New("Bilal") , human2 = Human.New("Inertia") ....

  • We learned that Classes have a special initialize method .. that is called when a new object is created from the Class
    - We can use this method to initialize properties of Objects .. Like we can set name, age, cuteness and loveliness of a Human
    - With our *perperties Trick, we were able to set as many properties as we could

  • We learned that Bilal Haider is a Ruby Programmer

Sort:  

Bilal bhai good job.

Thank you so much bro :)

Aur isky elwa Pakistan main koi watup group hai.main new hun

Bhai isky mutaliq Urdu main information mil skti Hai.

A useful science ..

This tutorial is very helpful. I am already thinking of giving rugby a go and I definitely will. We do appreciate your wisdom on this subject of programming. Thanks mate✌@bilal-haider
Followed and re-steemed👌