0
0
Rubyprogramming~15 mins

Method declaration with def in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Method declaration with def in Ruby
📖 Scenario: You are creating a simple calculator program that can add two numbers.
🎯 Goal: Build a Ruby method that takes two numbers and returns their sum.
📋 What You'll Learn
Create a method named add_numbers that takes two parameters: num1 and num2.
Inside the method, return the sum of num1 and num2.
Call the method with the numbers 5 and 7 and print the result.
💡 Why This Matters
🌍 Real World
Methods help organize code into reusable blocks, like a calculator that can add many pairs of numbers without rewriting code.
💼 Career
Knowing how to write methods is essential for any programming job, as it helps keep code clean and easy to maintain.
Progress0 / 4 steps
1
Create the method declaration
Write a method declaration named add_numbers that takes two parameters: num1 and num2. Do not add any code inside the method yet.
Ruby
Need a hint?

Use def to start the method and end to finish it.

2
Add the return statement inside the method
Inside the add_numbers method, write a line that returns the sum of num1 and num2.
Ruby
Need a hint?

Use return num1 + num2 to send back the sum.

3
Call the method with two numbers
Call the method add_numbers with the arguments 5 and 7, and save the result in a variable named result.
Ruby
Need a hint?

Use result = add_numbers(5, 7) to call the method and store the answer.

4
Print the result
Write a line to print the value of the variable result.
Ruby
Need a hint?

Use puts result to show the sum on the screen.