The beauty of object oriented design comes from the ability to build more efficient code that can be re-used. When new objects are created, they start at an empty state. When objects are built through classes, they can have pre-defined characteristics. We’re going to look at how classes are written using instance variables and instance methods.

Let’s imagine that we’re a dog breeder and we can create dogs using ruby!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class dog
  def initialize(name, type, gender, color )
    @name = name
    @type = type
    @species = species
    print "Your dog #{@name} has been created"
  end

  def name
    @name
  end

  def type
    @type
  end

  def gender
    @gender
  end

  def color
    @color
  end

  def name=(name)
    @name = new_name
  end
end

Instance Variables can be mistakened for normal variables. Just like normal variables you can assign them values, read them back and do stuff to them. However, when it comes to instance variables, they always start with the @ sign (also called the at sign) so you can quickly tell them apart from the common variable. Instance variables are also only visible to the object which they belong to. When an instance variable is defined in a class, they are accessible to all other methods within that class! How convenient!

When we build a class, such as our dog example, we start by defining the contents through initialize. We do this so that every time a new instance of this class is created, it will go through this class first. In our example, this initialize function will push the inputs (name, type, gender, color) into instance variables.

But looking at this code, it looks really repetitive. We like to keep things DRY. We can refactor these using attributes method family. Check out the refactored code below:

1
2
3
4
5
6
7
8
9
10
11
class dog
  attr_reader :type, :gender, :color
  attr_accessor :name

  def initialize(name, type, gender, color )
    @name = name
    @type = type
    @species = species
    print "Your dog #{@name} has been created"
  end
end

There are three commonly used attr_ functions. They must be placed in the beginning of the class definition. The attr_reader as shown in line 2 of the code above is the equivalent of

1
2
3
  def type
  @type
end

Any multiples of the attr_reader can be separated by commas. In line 3 we use the attr_accessor method which adds a method to read and write:

1
2
3
4
5
6
7
def name
  @name
end

def name=(name)
  @name = new_name
end

Should we only need a method to do write, we can use the attr_writer method.