support@90-10.dev

Ruby Classes & Objects

Everything in Ruby is an object and classes are the blueprints from which objects are created.

A class is a blueprint from which individual objects are created and encapsulates data and behavior that belong together:

class Person
  def initialize(name)
    @name = name
  end

  def greet
    puts "Hello, #{@name}!"
  end
end

In this example, we define a class called Person that has two methods: initialize and greet. The initialize method is called when a new object of the class is created. The greet method is a custom method that we defined for this class.

We can create an object of the Person class and call its methods like this:

obj = Person.new("John")
obj.greet

This will output the string "Hello, John!".

Naming conventions

  • class names start with an uppercase letter - camel case convention is used to multiword class names. e.g. BigCat
  • methods and variables (objects) start with a lowercase letter - underscores should be used separate words. e.g. blue_tiger

Initialiser

The initialize method is a special method that is called when a new instance of a class is created:

class Animal
  attr_accessor :legs
  def initialize(legs)
    @legs = legs
  end
end

pigeon = Animal.new(2)
puts pigeon.legs   # returns 2

The initialize method is not required in a class, but it is often used to ensure that objects are properly initialized when they are created. It can also be used to perform any additional setup that is required for the object to function properly.

Instance variables

Instance variables are used to store data that belongs to a specific object. They are prefixed with the @ symbol, and can be accessed and modified within the object's methods:

class Animal
  def initialize
    @legs = 4
  end
end

Instance variables are private to the object that they belong to, meaning that they cannot be accessed from outside the object's methods. However, we can define public methods in the class that allow us to read and modify the instance variables. The following code will return an error:

blue_tiger = Animal.new
puts blue_tiger.legs
# undefined method 'legs' for # (NoMethodError)

As the error suggest, we'll need to create a method to be able to show the value of the instance variable.

Instance methods

Instance methods are methods that belong to individual objects of a class. They are defined inside the class definition and can be called on any instance of the class.

Instance methods can be used to access and modify instance variables, which store data that belongs to a specific object. Instance methods can be used to define the behavior of objects and make them interact with each other.

class Animal
  def initialize
    @legs = 4
  end
  def legs
    return @legs 
  end
end

blue_tiger = Animal.new
puts blue_tiger.legs  # returns 4

A separate method will have to be added to allow one to store a different value for legs. We are going to use a legs= as a method name to make it easier on the eye:

class Animal
  def initialize
    @legs = 4
  end
  def legs
    return @legs 
  end
  def legs=(legs)
    @legs = legs
  end
end

pigeon = Animal.new
puts pigeon.legs   # returns 4
pigeon.legs = 2
puts pigeon.legs   # returns 2

NB: What looks like an assignment, pigeon.legs = 2, is in fact a method call: pigeon.legs=(2).

Attribute Accessors

Various attribute accessors are available to make it easier to write code. For our scenario above, we can use an attribute reader:

class Animal
  attr_reader :legs
  def initialize
    @legs = 4
  end
end

blue_tiger = Animal.new
puts blue_tiger.legs

Or, we can use attr_accessor to have both read and write:

class Animal
  attr_accessor :legs
  def initialize
    @legs = 4
  end
end

pigeon = Animal.new
puts pigeon.legs   # returns 4
pigeon.legs = 2
puts pigeon.legs   # returns 2

Class Variables

Ruby class variables are variables that are shared across all objects of a class. They are prefixed with the @@ symbol, and can be accessed and modified by all instances of the class. Class variables are often used to store data that is common to all objects of a class.

class Animal
  @@species = []
end

Class variables must be initialized before usage, and just like with the object variables.

Class Methods

Class methods are methods that belong to the class itself, rather than to individual objects of the class. They are defined with the self keyword, and can be called on the class itself, rather than on instances of the class.

class Animal
  @@species = []
  def self.species
    return @@species
  end
end

puts Animal.species.to_s  # returns []

Class methods can then be written to manipulate class variables:

class Animal
  @@species = []
  def self.species
    return @@species
  end
  def self.add(specie)
    @@species << specie
  end
end

puts Animal.species.to_s
Animal.add Animal.new
puts Animal.species.to_s  # returns [#<Animal:0x0000561997730a58>]

object ID

Every object in Ruby has a unique object ID, which can be obtained using the object_id method. We can see this by running the following code:

puts obj.object_id

This will output a number, which is the object ID of the obj object.

Ruby also has a special method called self, which refers to the current object. In the greet method, we used self to reference the object itself, so we could access the instance variable @name.


Classes and objects are an essential part of object-oriented programming in Ruby. They allow us to encapsulate data and behavior, and create reusable code that can be easily extended and modified.