Ruby - Object-Orientation Basics


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 = 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.


class Square 
  def initialize(side_length) 
    @side_length = side_length #   w ww  .ja  v a2s.  c om

  def area 
    @side_length * @side_length 

a = 
b = 
puts a.area 
puts b.area


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, 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

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