Bird
0
0

Identify the mistake in this Ruby code:

medium📝 Debug Q6 of 15
Ruby - Variables and Data Types
Identify the mistake in this Ruby code:
def check_nil(val)
  if val = nil
    "No value"
  else
    "Has value"
  end
end

puts check_nil(nil)
AUsing puts instead of print
BUsing nil instead of false in the condition
CMissing parentheses in method definition
DUsing assignment (=) instead of comparison (==) in the if condition
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the if condition

    The condition if val = nil assigns nil to val instead of comparing.
  2. Step 2: Correct the condition

    It should be if val == nil or better if val.nil?.
  3. Final Answer:

    Using assignment (=) instead of comparison (==) in the if condition -> Option D
  4. Quick Check:

    Assignment in condition always returns nil (falsey) [OK]
Quick Trick: Use == or .nil? for comparison, not = [OK]
Common Mistakes:
  • Confusing assignment (=) with equality (==)
  • Not using .nil? method for clarity

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes