Defining and Instantiating Classes

Learn how to define our own classes and create class instances.

Let’s start by creating a Calculator class and adding some methods to it, step by step.

In Ruby, we define a class like this:

Press + to interact
class Calculator
end

That’s all. It’s not a very useful class because it’s completely empty, but it’s a class.

Remember: A class is defined using the class keyword, a name, and the end keyword.

Use capital letters to define classes

Notice also that the class has the name Calculator, which starts with an uppercase letter. In Ruby, this is required, and we’d get an error if we tried to define a class called calculator.

Camel case and snake case

For class names that consist of several words, the Ruby community separates these words by uppercase letters, as in RubyStudyGroup. This is called CamelCase, because of the humps. This is contrary to variable and method names, for which we use underscores and keep everything lowercase—local_variable and method_name, for example. This is called snake_case.

Remember: Class names must start with an uppercase letter and should use CamelCase. Variable and method names should use snake_case.

OK, back to our class Calculator.

Since we’ve defined a full, valid class, we can now already use it to create a new, concrete calculator instance, an object from it.

We can think about the instance as the concrete calculator object that we can hold in our hands and use to perform actual calculations. The class, on the other hand, is more like the idea or concept of a calculator, like the idea of it that we have when we order a calculator online.

Here’s how to create a new, concrete instance from our class:

Calculator.new

The new method

The new method is defined on the class itself, which is also an object, so it can have methods. This method creates a new instance of the class and returns it.

Remember: The new method is defined on every class and returns a new instance of the class.

Let’s have a look at that object:

Press + to interact
p Calculator.new

The output may seem a bit strange and technical at first.

The #<...> format tells us that this object is not a simple thing like a number, string, or array. Instead, it tells us the name of the class, Calculator, and the internal ID that Ruby has assigned to this object.

Every object has its own unique internal object ID. We can simply ignore this ID most of the time.

We can also check that our new calculator instance is indeed an instance of the Calculator class:

Press + to interact
class Calculator
end
calculator = Calculator.new
puts calculator.class
puts calculator.is_a?(Calculator)

When we create a new instance of a class by way of calling the new method on that class, we’re instantiating that object. By calling Calculator.new, we instantiate a new calculator object.