0
0
Rubyprogramming~10 mins

Explicit return statement in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Explicit return statement
Start function
Execute code lines
Encounter return statement?
NoContinue executing
Yes
Return value immediately
Exit function
The function starts and runs code until it finds a return statement, then it immediately sends back the value and stops running.
Execution Sample
Ruby
def greet(name)
  return "Hello, #{name}!"
  "This line is ignored"
end

puts greet("Alice")
This code defines a function that returns a greeting string immediately, ignoring any code after the return.
Execution Table
StepActionCode LineReturn ValueNotes
1Function greet called with name='Alice'def greet(name)Function starts
2Return statement executedreturn "Hello, #{name}!""Hello, Alice!"Function returns immediately
3Code after return ignored"This line is ignored"Skipped
4Function endsendFunction exits with return value
5puts outputs return valueputs greet("Alice")Hello, Alice!Output to console
💡 Return statement causes immediate exit from function with value "Hello, Alice!"
Variable Tracker
VariableStartAfter Step 1After Step 2Final
nameundefinedAliceAliceAlice
return_valueundefinedundefined"Hello, Alice!""Hello, Alice!"
Key Moments - 2 Insights
Why does the line after the return statement not run?
Because the return statement immediately exits the function, so any code after it is skipped, as shown in execution_table row 3.
What value does the function send back when called?
The function returns the string "Hello, Alice!" right at the return statement, as seen in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the return value at step 2?
A"Hello, Alice!"
B"This line is ignored"
Cnil
D"Alice"
💡 Hint
Check the 'Return Value' column at step 2 in the execution_table.
At which step does the function stop running code inside it?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Notes' column where it says the function returns immediately.
If we remove the return statement, what happens to the output?
AThe function returns the first line's value
BThe function returns nil
CThe function returns the last line's value
DThe function causes an error
💡 Hint
In Ruby, without explicit return, the last evaluated expression is returned.
Concept Snapshot
def function_name(params)
  return value  # Immediately exits function with value
  # Code after return is ignored
end

Use return to send back a value early from a function.
Full Transcript
This example shows how a Ruby function uses an explicit return statement. When the function greet is called with "Alice", it runs until it hits the return line. At that point, it immediately sends back the greeting string and stops running. Any code after return is ignored. The output is "Hello, Alice!" printed to the console. This teaches that return ends the function early and sends back a value.