0
0
Rubyprogramming~15 mins

Why methods always return a value in Ruby - See It in Action

Choose your learning style9 modes available
Why methods always return a value in Ruby
📖 Scenario: Imagine you are baking cookies and you want to know how many cookies you made after baking. In Ruby, methods are like your baking process. They always give you a result back, just like you always get cookies after baking.
🎯 Goal: You will create a simple Ruby method that adds two numbers and see how it always returns a value, even if you don't explicitly say so.
📋 What You'll Learn
Create a method called add_numbers that takes two parameters a and b
Inside the method, add a and b without using the return keyword
Create a variable called result that calls add_numbers with 5 and 7
Print the value of result
💡 Why This Matters
🌍 Real World
Understanding that methods always return a value helps you write clear and predictable Ruby programs, like calculating totals or processing data.
💼 Career
Ruby developers often rely on implicit returns to write concise code, which is common in web development and scripting tasks.
Progress0 / 4 steps
1
Create the add_numbers method
Write a method called add_numbers that takes two parameters a and b. Inside the method, add a and b without using the return keyword.
Ruby
Need a hint?

In Ruby, the last line of a method is automatically returned. You don't need to write return.

2
Call the add_numbers method and store the result
Create a variable called result that calls the add_numbers method with the arguments 5 and 7.
Ruby
Need a hint?

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

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

Use puts result to show the output on the screen.

4
Observe the method return value
Run the program and observe that the method add_numbers returns the sum of 5 and 7, which is printed.
Ruby
Need a hint?

The output should be 12 because 5 + 7 = 12.