Ruby Classes

by Jim O'Neal on December 20, 2015

In this blog, I will discuss classes in Ruby, show an example class and talk about when to use isntance variables vs local variables.

A class is a set of rules, methods, and plans for how an object behaves. An object is always part of a class. Classes are very useful in Ruby because methods can be grouped together inside a class and made available to any object created that is part of that class.

In the example below, I have an example of a class called "Pet" which simulates a virtual pet. Inside the class are three methods that describe things you can do with the pet: walk it, feed it, and put it to bed. There is also a method to check to see if the pet is still alive after each action.

class Pet

  def initialize
    @happiness = 5
    @hunger = 5
    @energy = 5
    @alive_status = true
  end

  def walk
    @happiness += 1
    @hunger += 1
    @energy -= 1
    still_alive?
  end

  def feed
    @hunger -= 2
    @happiness += 1
    still_alive?
  end

  def put_to_bed
    @hunger += 1
    @energy += 2
    @happiness -= 1
    still_alive?
  end

  def still_alive?
    @alive_status = false if @happiness <= 0
    @alive_status = false if @hunger >= 10
    @alive_status = false if @energy <= 0
  end

end

In this example, there are variables that are created on the initialization of a new instance of "Pet". These variables are created as instance variables because they are intended to belong to that instance of the object of "Pet". They also need to be instance variables because these variables will be used in multiple methods inside the class. An instance variable is indicated by using "@" symbol in front of the variable name.

In my example code, the instance variables will be assigned to a new instance of Pet. These variables can then be used inside the walk, feed, and put_to_bed methods, as well as the still_alive? method. The variables are saved as part of the Pet object and do not belong specifically to an individual method like a local variable would be.

Classes and instance variables are part of what makes Ruby powerful and useful. For more information on both, visit this page, or read about them in David Black's "The Well Grounded Rubyist", or Chris Pine's "Learn to Program".