0
0
Rubyprogramming~30 mins

Module methods in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Module Methods in Ruby
📖 Scenario: You are building a simple calculator program that can perform basic math operations. To keep the code organized, you will use a Ruby module to group the math methods.
🎯 Goal: Create a Ruby module named Calculator with methods for addition and subtraction. Then call these methods to perform calculations.
📋 What You'll Learn
Create a module named Calculator
Inside the module, define a method add that takes two numbers and returns their sum
Inside the module, define a method subtract that takes two numbers and returns their difference
Call the add and subtract methods from the Calculator module and print the results
💡 Why This Matters
🌍 Real World
Modules help organize related methods in Ruby programs, making code easier to maintain and reuse.
💼 Career
Understanding modules is important for Ruby developers to write clean, modular, and reusable code in real projects.
Progress0 / 4 steps
1
Create the Calculator module
Create a Ruby module called Calculator.
Ruby
Need a hint?
Use the keyword module followed by the module name and end to define a module.
2
Add methods to the Calculator module
Inside the Calculator module, define a method called add that takes two parameters a and b and returns their sum. Also define a method called subtract that takes two parameters a and b and returns their difference.
Ruby
Need a hint?
Use def self.method_name to define module methods that can be called on the module itself.
3
Call the module methods
Call the add method from the Calculator module with arguments 10 and 5 and store the result in a variable called sum. Call the subtract method with arguments 10 and 5 and store the result in a variable called difference.
Ruby
Need a hint?
Call module methods using the module name followed by a dot and the method name.
4
Print the results
Print the values of sum and difference variables using two separate puts statements.
Ruby
Need a hint?
Use puts to print each variable on its own line.