0
0
Rubyprogramming~20 mins

Why class-level behavior matters in Ruby - See It in Action

Choose your learning style9 modes available
Why class-level behavior matters
📖 Scenario: Imagine you are creating a simple system to track books in a library. Each book has a title and an author. You want to count how many books have been created in total, no matter which book it is.
🎯 Goal: You will build a Ruby class Book that keeps track of how many book objects have been created using class-level behavior.
📋 What You'll Learn
Create a class called Book
Add an instance method initialize that takes title and author parameters
Add a class variable @@count to count how many books have been created
Increment @@count each time a new Book is created
Add a class method self.count that returns the total number of books created
Create at least two Book objects with given titles and authors
Print the total number of books created using the class method
💡 Why This Matters
🌍 Real World
Counting objects like books, users, or orders is common in software to track totals or limits.
💼 Career
Understanding class-level behavior is important for designing classes that manage shared data or resources in Ruby applications.
Progress0 / 4 steps
1
Create the Book class with initialize method
Create a class called Book with an initialize method that takes title and author as parameters and sets them as instance variables.
Ruby
Need a hint?

Use @title and @author to store the values inside the object.

2
Add a class variable to count books
Inside the Book class, add a class variable @@count and set it to 0 before the initialize method.
Ruby
Need a hint?

Class variables start with @@ and are shared by all instances.

3
Increment count when a book is created
Inside the initialize method, add code to increase @@count by 1 each time a new Book object is created.
Ruby
Need a hint?

Use @@count += 1 to add one to the class variable.

4
Add class method and print total books
Add a class method self.count inside the Book class that returns @@count. Then create two Book objects with titles '1984' and 'Brave New World' and authors 'George Orwell' and 'Aldous Huxley'. Finally, print the total number of books created by calling Book.count.
Ruby
Need a hint?

Define def self.count to make a class method. Use puts Book.count to print the total.