Skip to main content
March 23, 2026Noble Desktop Publishing Team/6 min read

Ruby Fundamentals: Classes & Objects

Master Ruby's Object-Oriented Programming Foundation for Rails Development

Ruby vs Rails Foundation

Ruby is the programming language, while Ruby on Rails is a framework built on Ruby. Understanding Ruby syntax is essential before diving deep into Rails development.

Topics Covered in This Ruby on Rails Tutorial:

Understanding Ruby's object-oriented foundation and defining your first class

Core Ruby Concepts You'll Learn

Object-Oriented Fundamentals

Everything in Ruby is an object containing variables and methods. Learn how objects model real-world entities to make code more readable and powerful.

Methods and Classes

Define reusable blocks of code with methods and create blueprints for objects using classes. Master the building blocks of Ruby programming.

Interactive Ruby Practice

Use IRB to test Ruby concepts hands-on. Practice string concatenation, method calls, and object instantiation in real-time.

Exercise Overview

Ruby is a programming language, and Ruby on Rails is a web framework built on Ruby's foundation. Many developers jump straight into Rails without mastering Ruby fundamentals—a mistake that inevitably leads to frustration and inefficiency down the road.

In this tutorial series, we're stepping back from Rails and web development to focus on Ruby itself. You'll master essential object-oriented concepts like classes, methods, and properties—the building blocks that make Rails possible. Think of this as investing time now to save countless hours later. When you return to Rails development, these concepts will feel intuitive rather than mysterious, allowing you to write more elegant, maintainable code.

Learning Path Structure

1

Step Away from Rails

Temporarily focus on pure Ruby language fundamentals without web framework complexity

2

Learn Core Concepts

Master classes, methods, properties and object-oriented programming principles

3

Apply to Rails

Use Ruby foundation knowledge for deeper Rails development understanding

Everything in Ruby is an Object

Ruby's philosophy is beautifully simple: everything is an object. Unlike languages that treat primitives and objects differently, Ruby maintains consistency—numbers, strings, classes, and even methods are all objects with their own properties and behaviors. This object-oriented foundation isn't just academic theory; it's what makes Ruby so expressive and powerful in real-world applications.

An object combines data (variables) and behavior (methods) into a cohesive unit that models real-world entities. Instead of scattered functions manipulating disconnected data, objects provide structure, encapsulation, and clarity. We'll explore these concepts by building a Cat object from the ground up, demonstrating how object-oriented thinking translates abstract programming concepts into intuitive, maintainable code.

  1. Open Terminal.

  2. We'll use Interactive Ruby (IRB), Ruby's built-in REPL (Read-Eval-Print Loop), to experiment with Ruby syntax in real-time. This interactive environment is invaluable for testing concepts and debugging—professional Ruby developers use IRB daily. Start IRB by typing the following and pressing Return:

    irb

    NOTE: The numbers in your Terminal prompt (like 3.2.0 :001) show your Ruby version followed by the current line number. As of 2026, Ruby 3.2+ is standard, offering significant performance improvements over earlier versions.

  3. Let's begin modeling our cat with its most essential behavior. Every cat needs to meow, so type:

    puts "Meow!"

    IRB responds by printing Meow! followed by nil on the next line. This demonstrates Ruby's consistent return value system: every expression returns something, and puts returns nil after performing its side effect (printing to the console).

  4. That nil return value is visually distracting. For cleaner output, simply type:

    "Meow!"

    Now Terminal displays "Meow!" cleanly because a string literal evaluates to itself. This distinction between expressions with side effects (puts) and pure expressions (string literals) is fundamental to understanding Ruby's design.

  5. Let's explore string manipulation—a cornerstone of web development. Ruby uses the + operator for string concatenation. Type the following, paying careful attention to spacing:

    "Meow! " + "I am hungry"

    Terminal returns "Meow! I am hungry". The space after "Meow!" is preserved, demonstrating how Ruby treats strings as immutable sequences of characters. This concatenation method, while simple, creates new string objects—something to consider for performance in production applications.

  6. Ruby's + operator exhibits polymorphism—it behaves differently based on the object types involved. With numbers, it performs mathematical addition:

    2 + 3

    Terminal returns 5, demonstrating how the same operator can have different behaviors depending on context—a key principle of object-oriented programming.

  7. This distinction between data types becomes crucial in real applications. When you wrap numbers in quotes, they become strings with entirely different behavior:

    "2" + "3"

    Terminal returns "23", concatenating rather than adding. This type coercion behavior is common in web development where form inputs arrive as strings, requiring explicit conversion for mathematical operations.

Now that we understand Ruby's basic syntax and object behavior, let's create reusable code blocks through methods.

Object-oriented programming is simply meant to model the real-world
Ruby's approach to making code more readable and powerful by organizing functionality into objects that represent real entities

String Operations in Ruby

FeatureNumbersStrings
Addition Operation2 + 3 = 5"2" + "3" = "23"
ConcatenationMathematical sumText joining
Return ValueNumeric resultCombined string
Recommended: Use quotes carefully - they change how Ruby interprets and processes data

Defining a Method

  1. Methods are the fundamental building blocks of object-oriented programming—reusable code blocks that encapsulate specific behaviors. Ruby's method syntax is elegantly simple. Create your first method by typing (IRB will handle indentation automatically):

    def say_meow
       "Meow!"
       end
  2. Execute your method by calling its name:

    say_meow

    IRB prints "Meow!" each time you call say_meow. This reusability is method's primary advantage—write once, use anywhere. Try calling it multiple times using the Up Arrow to repeat commands.

    Let's dissect this method definition:

    • def is Ruby's method definition keyword, signaling the start of a new method
    • say_meow is the method name, following Ruby's snake_case convention
    • "Meow!" is the method body—the code executed when called
    • end closes the method definition, maintaining Ruby's readable block structure

    Professional tip: If you make typing errors and need to cancel a multi-line command, press Control–C (not Command!) to interrupt the current operation. You may need to press it multiple times for complex nested structures.

Methods provide reusability, but they need a home. This is where classes come in—templates that organize methods and data into cohesive objects.

IRB Auto-Indentation

Don't worry about typing indentation spaces - Terminal will automatically indent your code when you hit Return in Interactive Ruby.

Method Structure Components

def keyword

Stands for definition and indicates you're creating a new method. Always precedes the method name.

Method Name

The identifier used to call the method later. Use descriptive names like say_meow for clarity.

Method Body

The code that executes when the method is called. Contains the actual functionality you want to perform.

end keyword

Signifies that the method definition is complete. Required to close the method block properly.

Defining a Class

  1. We have a method, but no object to contain it. Classes solve this by providing templates for creating objects. Define a Cat class:

    class Cat
       def say_meow
          "Meow!"
          end
       end

    Notice the double end—this isn't a typo! The first closes the say_meow method, the second closes the Cat class. This nested structure is common in Ruby and becomes second nature with practice.

    Your Cat class follows Ruby conventions: class names use PascalCase (capitalized first letter), and the structure mirrors method definition but with class instead of def.

  2. Let's try to make our cat speak:

    Cat.say_meow
  3. You'll see an error message—and that's exactly what we want! This error illustrates a crucial object-oriented concept: the difference between classes and instances. You've created a blueprint (class) but no actual cat (instance) yet.

    Think of a class as an architectural blueprint. The blueprint describes what a house should look like, but you can't live in the blueprint—you need to build an actual house from it. Similarly, our Cat class defines what cats can do, but we need to create an actual cat instance to use those behaviors.

  4. Create a cat instance and make it speak:

    fluffy = Cat.new
    fluffy.say_meow

    Success! Terminal returns "Meow!" as expected. You've just witnessed instantiation—creating an object from a class template.

    Breaking down this code:

    • fluffy = Cat.new creates a new Cat instance and assigns it to the variable fluffy. The .new method is Ruby's standard constructor, available on every class
    • fluffy.say_meow calls the say_meow method on our specific cat instance using dot notation—Ruby's syntax for accessing object methods and properties
  5. When you typed fluffy = Cat.new, IRB displayed something like #<Cat:0x007f8ebaleef88>. This cryptic string is Ruby's default object representation, showing the class name (Cat) followed by a unique memory identifier. Every object gets a unique identifier, confirming that each instance is distinct in memory.

  6. Let's prove that classes can generate multiple unique instances:

    george = Cat.new
    george.say_meow

    George also says "Meow!", confirming he has the same capabilities as Fluffy. However, notice George's unique identifier differs from Fluffy's (something like #<Cat:0x007f8eb904ceb0>). They're separate objects created from the same template—exactly how object-oriented programming should work.

    This instance creation pattern is fundamental to Rails development, where you'll create multiple instances of models like User, Post, or Product, each with unique data but shared behaviors.

  7. Keep Terminal open—we'll expand on these Cat objects in the next exercise, adding more sophisticated behaviors and properties.

Double End Statement

When defining classes with methods in IRB, you must type 'end' twice - once for the method and once for the class. This is not a typo.

Class vs Instance Behavior

FeatureClass CallInstance Call
SyntaxCat.say_meowfluffy.say_meow
ResultError message"Meow!"
ReasonNo actual cat existsSpecific cat instance created
Recommended: Always create an instance before calling instance methods

Object Instantiation Process

1

Define the Class

Create a template or blueprint that describes what objects of this type can do

2

Instantiate the Object

Use ClassName.new to create an actual instance from the class template

3

Call Instance Methods

Use dot syntax (object.method) to execute methods on the specific instance

Object Unique Identifiers

When you create objects in Ruby, each gets a unique identifier like #<Cat:0x007f8ebaleef88>. This confirms that different instances are separate objects, even if they're from the same class.

Key Takeaways

1Ruby is the foundational programming language that powers the Ruby on Rails framework, making Ruby syntax knowledge essential for Rails development
2Everything in Ruby is an object containing both variables and methods, designed to model real-world entities and make code more readable and powerful
3Interactive Ruby (IRB) provides a testing environment where you can experiment with Ruby code and see return values immediately
4Methods are reusable blocks of code defined with 'def' keyword and closed with 'end', allowing you to encapsulate functionality for repeated use
5Classes serve as templates or blueprints for creating objects, defining what instances of that class can do through embedded methods
6You must instantiate a class using ClassName.new before calling instance methods - calling methods directly on classes results in errors
7String concatenation with the plus operator joins text together, while the same operator performs mathematical addition on numbers
8Each object instance receives a unique identifier in Ruby, confirming that separate instances are distinct even when created from the same class template

RELATED ARTICLES