0
0
Rubyprogramming~20 mins

Send for calling methods dynamically in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Send for calling methods dynamically
📖 Scenario: Imagine you have a simple calculator that can perform different operations like addition, subtraction, multiplication, and division. You want to call these operations dynamically based on user input.
🎯 Goal: Build a Ruby program that uses send to call calculator methods dynamically.
📋 What You'll Learn
Create a class Calculator with methods add, subtract, multiply, and divide
Create an instance of Calculator called calc
Create a variable operation that stores the method name as a symbol
Use send on calc with operation and two numbers to get the result
Print the result
💡 Why This Matters
🌍 Real World
Dynamic method calling is useful when you want to choose actions at runtime, like in calculators, menus, or command handlers.
💼 Career
Understanding <code>send</code> helps in metaprogramming and building flexible Ruby applications that adapt to different inputs or commands.
Progress0 / 4 steps
1
Create the Calculator class with methods
Create a class called Calculator with four methods: add, subtract, multiply, and divide. Each method takes two parameters a and b and returns the result of the operation.
Ruby
Need a hint?

Define each method inside the class with two parameters and return the calculation.

2
Create an instance and set operation variable
Create an instance of Calculator called calc. Then create a variable called operation and set it to the symbol :multiply.
Ruby
Need a hint?

Use Calculator.new to create the instance and assign :multiply to operation.

3
Use send to call the method dynamically
Use send on the calc object with the operation variable and the numbers 6 and 7 as arguments. Store the result in a variable called result.
Ruby
Need a hint?

Use calc.send(operation, 6, 7) to call the method stored in operation.

4
Print the result
Print the value of the variable result.
Ruby
Need a hint?

Use puts result to display the output.