0
0
Rubyprogramming~10 mins

Parameters with default values in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Parameters with default values
Define method with default parameters
Call method with arguments?
NoUse default values
Yes
Assign passed arguments to parameters
Execute method body
Return result
End
The method is defined with default values for parameters. When called, if arguments are missing, defaults are used; otherwise, passed values are used.
Execution Sample
Ruby
def greet(name = "Friend")
  "Hello, #{name}!"
end

puts greet("Alice")
puts greet
Defines a method with a default parameter and calls it with and without an argument.
Execution Table
StepMethod CallParameter 'name'ActionOutput
1greet("Alice")"Alice"Use passed argument"Hello, Alice!"
2puts output-Print outputHello, Alice!
3greet"Friend"Use default value"Hello, Friend!"
4puts output-Print outputHello, Friend!
5--End of calls-
💡 No more method calls; execution ends.
Variable Tracker
VariableStartAfter Call 1After Call 2Final
name-"Alice""Friend"-
output-"Hello, Alice!""Hello, Friend!"-
Key Moments - 2 Insights
Why does the method use "Friend" when no argument is given?
Because the parameter 'name' has a default value "Friend" defined, so when no argument is passed (see execution_table row 3), it uses that default.
What happens if we pass an argument to the method?
The passed argument overrides the default value (see execution_table row 1), so 'name' becomes the passed value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'name' during the second method call?
Anil
B"Alice"
C"Friend"
D"Hello"
💡 Hint
Check execution_table row 3 where the method is called without arguments.
At which step is the output "Hello, Alice!" printed?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 2 where puts prints the output.
If we change the default value to "Guest", what will be printed at step 4?
A"Hello, Guest!"
B"Hello, Friend!"
C"Hello, nil!"
D"Hello, Alice!"
💡 Hint
Refer to variable_tracker for default value changes affecting output.
Concept Snapshot
def method_name(param = default)
  # method body
end

- If argument is passed, param = argument
- If no argument, param = default
- Allows flexible calls with optional arguments
Full Transcript
This example shows how Ruby methods can have parameters with default values. When the method greet is called with an argument like "Alice", it uses that value. When called without an argument, it uses the default "Friend". The execution table traces each call and output. The variable tracker shows how 'name' changes. This helps beginners understand how default parameters work in Ruby methods.