Ruby - Object-Orientation Basics

Introduction

A class is a blueprint for objects.

You can have one class called Shape, but with it you can create multiple instances of Shape objects.

All of the shape objects have the methods and attributes defined by the Shape class.

An object is an instance of a class.

If Shape is the class, then x = Shape.new creates a new Shape instance and makes x reference that object.

You would then say x is a Shape object, or an object of class Shape.

Local, Global, Object, and Class Variables

Here's a simple demonstration of a class with two methods.

Demo

class Square 
  def initialize(side_length) 
    @side_length = side_length # from   w  ww.j  a  v  a  2  s .  c  o  m
  end 

  def area 
    @side_length * @side_length 
  end 
end 

a = Square.new(10) 
b = Square.new(5) 
puts a.area 
puts b.area

Result

The first method in the Square class is initialize.

initialize is a special method that's called when a new object is created.

When you call Square.new(10), the Square class creates a new object instance of itself, and then calls initialize upon that object.

Here, initialize accepts a single argument into side_length as passed by Square.new(10).

And then assigns the number 10 referenced by side_length to a variable called @side_length.

The @ symbol before the variable name marks an attribute.

Related Topics