Bird
0
0

You want a Ruby method to return the first non-nil value from two expressions. Which method definition correctly uses Ruby's automatic return to achieve this?

hard📝 Application Q15 of 15
Ruby - Methods
You want a Ruby method to return the first non-nil value from two expressions. Which method definition correctly uses Ruby's automatic return to achieve this?
def first_non_nil(a, b)
  # fill in
end
Adef first_non_nil(a, b) a || b end
Bdef first_non_nil(a, b) return a if a return b end
Cdef first_non_nil(a, b) puts a || b end
Ddef first_non_nil(a, b) a b end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want the method to return the first non-nil value between a and b.
  2. Step 2: Check each option's return value

    def first_non_nil(a, b) a || b end returns a || b which evaluates to first non-nil value automatically. def first_non_nil(a, b) return a if a return b end uses explicit returns but is longer. def first_non_nil(a, b) puts a || b end prints but returns nil. def first_non_nil(a, b) a b end returns b always because last line is b.
  3. Final Answer:

    def first_non_nil(a, b) a || b end -> Option A
  4. Quick Check:

    Last expression returns first non-nil [OK]
Quick Trick: Use last line expression to return desired value without return [OK]
Common Mistakes:
  • Using puts instead of returning value
  • Writing multiple return statements unnecessarily
  • Returning wrong line's value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes