Bird
0
0

How would you modify this method to provide a default value for name so it prints "Hello, Guest!" if no argument is given?

hard📝 Application Q9 of 15
Ruby - Methods
How would you modify this method to provide a default value for name so it prints "Hello, Guest!" if no argument is given?
def greet(name)
  "Hello, #{name}!"
end
Adef greet(name = "Guest") "Hello, #{name}!" end
BAll of the above
Cdef greet(name) if name.nil? name = "Guest" end "Hello, #{name}!" end
Ddef greet(name) name ||= "Guest" "Hello, #{name}!" end
Step-by-Step Solution
Solution:
  1. Step 1: Understand default arguments

    Ruby allows default values in method parameters like name = "Guest".
  2. Step 2: Alternative ways to set default

    Options B and C set default inside method body using conditional assignment or if statement.
  3. Step 3: Confirm all options work

    All three options correctly ensure name is "Guest" if no argument or nil is passed.
  4. Final Answer:

    All of the above -> Option B
  5. Quick Check:

    Default args or conditional assignment work [OK]
Quick Trick: Use default params or conditional assignment for defaults [OK]
Common Mistakes:
  • Not handling nil argument
  • Forgetting default value syntax
  • Assuming default works without code

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes