0
0
Rubyprogramming~15 mins

Class methods with self prefix in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Class methods with self prefix in Ruby
📖 Scenario: You are creating a simple calculator class in Ruby. This calculator will have methods that belong to the class itself, not to individual objects. This means you can call these methods directly on the class without making a new calculator object.
🎯 Goal: Build a Ruby class called Calculator with class methods using the self prefix. These methods will perform basic math operations like addition and subtraction.
📋 What You'll Learn
Create a class called Calculator
Add a class method called add that takes two numbers and returns their sum
Add a class method called subtract that takes two numbers and returns their difference
Call both class methods and print their results
💡 Why This Matters
🌍 Real World
Class methods are useful when you want to group related functions that don't need an object. For example, utility functions like math operations or configuration helpers.
💼 Career
Understanding class methods is important for Ruby developers to write clean, reusable code and to organize functionality logically within classes.
Progress0 / 4 steps
1
Create the Calculator class
Create a class called Calculator with no methods inside it yet.
Ruby
Need a hint?

Use the class keyword followed by the class name Calculator.

2
Add the add class method
Inside the Calculator class, add a class method called self.add that takes two parameters a and b and returns their sum.
Ruby
Need a hint?

Use def self.add(a, b) to define the class method.

3
Add the subtract class method
Inside the Calculator class, add a class method called self.subtract that takes two parameters a and b and returns the result of a - b.
Ruby
Need a hint?

Define the method with def self.subtract(a, b) and return a - b.

4
Call and print the class methods
Call the class methods Calculator.add(10, 5) and Calculator.subtract(10, 5) and print their results using puts.
Ruby
Need a hint?

Use puts Calculator.add(10, 5) and puts Calculator.subtract(10, 5) to print the results.