0
0
Rubyprogramming~15 mins

Proc creation and call in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Proc creation and call
📖 Scenario: Imagine you are building a simple calculator that can perform different operations. You want to use Ruby's Proc objects to store these operations and call them when needed.
🎯 Goal: Create a Proc that adds two numbers, store it in a variable, and then call it to get the result.
📋 What You'll Learn
Create a Proc that takes two numbers and returns their sum.
Store the Proc in a variable called add_proc.
Call the add_proc with the numbers 5 and 7.
Print the result of the Proc call.
💡 Why This Matters
🌍 Real World
Procs let you store blocks of code to reuse later, like saving a recipe to cook anytime.
💼 Career
Understanding Procs helps in Ruby programming for flexible and reusable code, common in web development and automation.
Progress0 / 4 steps
1
Create a Proc that adds two numbers
Create a Proc called add_proc that takes two parameters a and b and returns their sum.
Ruby
Need a hint?

Use Proc.new { |a, b| a + b } to create the Proc.

2
Call the Proc with two numbers
Call the add_proc with the numbers 5 and 7 and store the result in a variable called result.
Ruby
Need a hint?

Use add_proc.call(5, 7) to call the Proc.

3
Print the result
Print the value of the variable result using puts.
Ruby
Need a hint?

Use puts result to print the sum.

4
Use the Proc with different numbers
Call the add_proc with the numbers 10 and 15 and print the result directly using puts.
Ruby
Need a hint?

Use puts add_proc.call(10, 15) to print the new sum.