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

Defining a class

class Animal
end

To create an Animal object, we use the new method:

blue_tiger = Animal.new

An object contains both state (instance variables) and logic (instance methods).

Instance variables

We're defining an instance variable legs for the Animal class inside the initialize method:

class Animal
  def initialize
    @legs = 4
  end
end

Instance variables are private by design - i.e. they are not accessible from outside. 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 method

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

Initialiser

One final observation - the initialiser can also have parameters that can be used to set the initial state for the object's instance variables.

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

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

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