ruby class can be used to create objects. Classes are the cornerstone of object orientated programming (oop).

A ruby program can have multiple objects. An object is essentially a collection of methods and variables. Each object has its own values, but the methods and variable names derrive from the class definition.

Download Free Ruby Ebook

Classes in ruby

Class example

This concept can be challenging to grasp, and is easier to understand with an example.
The ruby program below creates an object from the defined class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/ruby

class Cube

def initialize(length)
@length = length
end

def showLength
puts "Size is #@length x #@length x #@length"
end
end

# create object
object1 = Cube.new(3)
object1.showLength

# create another object
object2 = Cube.new(4)
object2.showLength

The above program defines a class (cube) which has a property and a method. Then two objects are created.

The attributes of the objects are set, and shown using the class method.
The output should be similar to:

1
2
Cube is 3x3x3
Cube is 4x4x4

Exercises

  1. Create two objects from a class.
  2. Can an object create a class?