Ruby Loops Iterators Blocks Methods and Classes

This chapter explores Ruby loops, iterators, blocks, methods, and classes, which together allow for modular, reusable, and object-oriented programming. These constructs form the backbone of Ruby’s programming paradigm.

Chapter Goals

  • Understand the purpose and usage of loops, iterators, blocks, methods, and classes in Ruby.
  • Learn how to encapsulate logic into methods and organize methods into classes.
  • Explore the principles of object-oriented programming (OOP) in Ruby.
  • Implement best practices for writing clear, efficient, and reusable code using OOP principles.

Key Characteristics of Ruby Loops, Iterators, Blocks, Methods, and Classes

  • Iteration: Repeat code execution over a range, array, or condition.
  • Block Modularity: Use blocks to encapsulate reusable logic passed to methods.
  • Reusable Methods: Encapsulate functionality into methods for reusability.
  • Object Orientation: Use classes to represent objects with attributes and methods.
  • Encapsulation: Combine data and behavior in classes for modularity.

Basic Rules for Loops, Iterators, Blocks, Methods, and Classes

  • Use loops (while, until) for condition-based iterations.
  • Prefer iterators (each, map, times) for iterating over collections.
  • Use methods to encapsulate logic and improve code reuse.
  • Use classes to encapsulate related data and behavior.
  • Test loops, iterators, methods, and classes with edge cases to ensure correct behavior.

Best Practices

  • Write descriptive variable and method names for clarity.
  • Avoid deeply nested blocks and methods; refactor logic if necessary.
  • Document the purpose and structure of methods and classes for maintainability.
  • Use iterators, blocks, and methods to make code more Ruby-idiomatic.
  • Use classes to model real-world objects and relationships.

Syntax Table

Serial No Type Syntax/Example Description
1 Class Definition class ClassName \n code \n end Defines a new class.
2 Method in Class def method_name(parameters) \n code \n end Defines a method within a class.
3 Object Instantiation object = ClassName.new Creates an instance of a class.
4 Instance Variables @variable Stores data specific to an object.
5 Getter Method attr_reader :attribute Defines a method to access an attribute.
6 Setter Method attr_writer :attribute Defines a method to modify an attribute.
7 Getter and Setter attr_accessor :attribute Defines both getter and setter methods.

Syntax Explanation

Classes in Ruby

What are Classes in Ruby?

Classes are blueprints for creating objects, encapsulating related data and behavior.

Syntax

class ClassName

  def initialize(parameters)

    @variable = parameters

  end

 

  def method_name

    code

  end

end

 

# Creating an object

object = ClassName.new(arguments)

object.method_name

Detailed Explanation

  • Classes are defined using the class keyword.
  • The initialize method is a constructor that sets up the object’s initial state.
  • Instance variables (@variable) store data specific to each object.

Example

class Person

  def initialize(name, age)

    @name = name

    @age = age

  end

 

  def introduce

    “Hi, I’m \#{@name} and I’m \#{@age} years old.”

  end

end

 

person = Person.new(“Alice”, 30)

puts person.introduce

Example Explanation

  • Creates a Person class with attributes name and age.
  • Defines a method introduce to display a personalized introduction.

Accessor Methods

What are Accessor Methods?

Accessor methods allow controlled access to instance variables.

Syntax

class ClassName

  attr_accessor :attribute

end

 

object = ClassName.new

object.attribute = value

puts object.attribute

Detailed Explanation

  • attr_reader creates a getter method.
  • attr_writer creates a setter method.
  • attr_accessor creates both getter and setter methods.

Example

class Car

  attr_accessor :make, :model

 

  def initialize(make, model)

    @make = make

    @model = model

  end

end

 

car = Car.new(“Toyota”, “Corolla”)

puts car.make

car.model = “Camry”

puts car.model

Example Explanation

  • Accesses and modifies the attributes make and model using accessor methods.

Class Methods

What are Class Methods?

Class methods are methods that belong to the class itself, not individual objects.

Syntax

class ClassName

  def self.method_name

    code

  end

end

 

ClassName.method_name

Detailed Explanation

  • Class methods are prefixed with self..
  • Useful for actions that are relevant to the class as a whole.

Example

class Calculator

  def self.add(a, b)

    a + b

  end

end

 

puts Calculator.add(5, 3)

Example Explanation

  • Defines a class method add for performing addition.
  • Calls the method directly on the Calculator class.

Real-Life Project

Project Name: Library Management System

Project Goal

Create a simple library management system using classes and methods.

Code for This Project

class Book

  attr_accessor :title, :author

  def initialize(title, author)

    @title = title

    @author = author

  end

  def details

    "\#{@title} by \#{@autho}
end
class Library

  def initialize

    @books = []

  end

  def add_book(book)

    @books << book

  end

  def list_books

    @books.each { |book| puts book.details }

  end

end


library = Library.new

book1 = Book.new("1984", "George Orwell")

book2 = Book.new("To Kill a Mockingbird", "Harper Lee")


library.add_book(book1)

library.add_book(book2)

library.list_books

Steps

  1. Define a Book class with attributes title and author.
  2. Define a Library class to manage a collection of books.
  3. Implement methods to add and list books in the library.
  4. Create objects and use the methods to simulate a library system.

Expected Output

1984 by George Orwell

To Kill a Mockingbird by Harper Lee

Project Explanation

  • Demonstrates object-oriented programming by modeling a library system.
  • Encapsulates data and behavior in classes for modularity and reuse.

Insights

Ruby classes provide a foundation for building modular, reusable, and scalable programs. Understanding their syntax and usage ensures cleaner and more maintainable code.

Key Takeaways

  • Use classes to model real-world objects and encapsulate related data and behavior.
  • Leverage accessor methods for controlled access to instance variables.
  • Use class methods for actions relevant to the entire class.
  • Combine classes with loops, iterators, blocks, and methods for efficient and organized Ruby programs.