Bird
0
0

Consider this Ruby method:

hard📝 Application Q9 of 15
Ruby - Methods
Consider this Ruby method:
def format_name(first, last = "Smith", middle = nil)
  if middle
    "#{first} #{middle} #{last}"
  else
    "#{first} #{last}"
  end
end

What will format_name("John") return?
A"John nil Smith"
B"John Smith"
C"John Smith"
DError due to missing middle argument
Step-by-Step Solution
Solution:
  1. Step 1: Analyze default parameters

    last defaults to "Smith", middle defaults to nil.
  2. Step 2: Evaluate method call format_name("John")

    Only first is provided, last = "Smith", middle = nil. The else branch runs, returning "John Smith".
  3. Final Answer:

    "John Smith" -> Option B
  4. Quick Check:

    Default parameters fill missing arguments; nil triggers else branch [OK]
Quick Trick: Default nil triggers else branch in conditional [OK]
Common Mistakes:
  • Expecting nil to print as string
  • Assuming error when optional argument missing
  • Confusing spaces in output

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes