0
0
Rubyprogramming~30 mins

Define_method with closures in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Define_method with closures
📖 Scenario: Imagine you are creating a simple calculator that can perform different operations like addition and multiplication. You want to create these operations dynamically using Ruby's define_method and closures.
🎯 Goal: Build a Ruby class called Calculator that uses define_method with closures to create methods for addition and multiplication dynamically.
📋 What You'll Learn
Create a class called Calculator
Use define_method to add methods dynamically
Use closures to capture operation logic inside the methods
Create methods called add and multiply dynamically
Each method should take two numbers and return the correct result
💡 Why This Matters
🌍 Real World
Dynamic method creation is useful when you want to generate similar methods without repeating code, like in calculators, data models, or API clients.
💼 Career
Understanding closures and dynamic method definitions helps in writing flexible, maintainable Ruby code often required in web development and automation.
Progress0 / 4 steps
1
Create the Calculator class
Write a class called Calculator with no methods inside.
Ruby
Need a hint?

Use the class keyword followed by Calculator and end to define the class.

2
Add a config hash for operations
Inside the Calculator class, create a constant called OPERATIONS that is a hash with keys :add and :multiply. The values should be lambdas that take two arguments and return their sum and product respectively.
Ruby
Need a hint?

Use a hash with keys :add and :multiply and assign lambdas using ->(a, b) { ... }.

3
Define methods dynamically using define_method and closures
Inside the Calculator class, use OPERATIONS.each to loop over each operation. For each key and lambda, use define_method with the key as the method name and the lambda as the method body. The method should take two parameters a and b and return the result of the lambda.
Ruby
Need a hint?

Use define_method(name) do |a, b| ... end inside the loop and call the lambda with operation.call(a, b).

4
Create an instance and test the methods
Create an instance of Calculator called calc. Then print the result of calc.add(5, 3) and calc.multiply(4, 6) each on a new line.
Ruby
Need a hint?

Create calc = Calculator.new and use puts calc.add(5, 3) and puts calc.multiply(4, 6).