0
0
Rubyprogramming~5 mins

Parameters with default values in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a parameter with a default value in Ruby?
A parameter with a default value is a method parameter that has a preset value. If no argument is given when calling the method, Ruby uses this default value.
Click to reveal answer
beginner
How do you define a method with a default parameter in Ruby?
You assign a value to the parameter in the method definition, like def greet(name = "Friend"). If no argument is passed, "Friend" is used.
Click to reveal answer
beginner
What happens if you call a Ruby method with a default parameter and provide an argument?
The provided argument replaces the default value for that call. The method uses the argument you give instead of the default.
Click to reveal answer
intermediate
Can you mix parameters with and without default values in Ruby methods?
Yes, you can. Parameters without default values should come first, followed by those with default values to avoid errors.
Click to reveal answer
beginner
Example: What does this method print?<br>
def say(message = "Hello")
  puts message
end

say
say("Hi")
It prints:<br>
Hello
Hi
<br>First call uses the default "Hello". Second call uses the argument "Hi".
Click to reveal answer
In Ruby, how do you set a default value for a method parameter?
ABy setting the value inside the method body
BBy assigning a value in the method definition, like <code>def m(param = 5)</code>
CBy calling the method with no arguments
DBy using a global variable
What happens if you call a Ruby method with a default parameter but provide an argument?
AThe default value is ignored and the argument is used
BAn error occurs
CThe method uses the default value anyway
DThe method ignores the argument
Which order should parameters be in when mixing default and non-default values in Ruby?
ADefault parameters first, then non-default
BOnly default parameters are allowed
COrder does not matter
DNon-default parameters first, then default parameters
What will this Ruby code print?<br>
def greet(name = "Guest")
  puts "Hi, #{name}!"
end
greet("Alice")
AHi, Alice!
BHi, Guest!
CHi, !
DError
Why are default parameters useful in Ruby methods?
AThey force all arguments to be provided
BThey make methods slower
CThey allow methods to be called with fewer arguments
DThey prevent method calls
Explain how to use parameters with default values in Ruby methods and why they are helpful.
Think about how you can make a method flexible with fewer required inputs.
You got /4 concepts.
    Describe the correct order of parameters when mixing default and non-default values in Ruby methods and why order matters.
    Consider how Ruby matches arguments to parameters.
    You got /4 concepts.