Bird
0
0

Which of the following is the correct syntax for a case/when statement in Ruby?

easy📝 Syntax Q12 of 15
Ruby - Control Flow

Which of the following is the correct syntax for a case/when statement in Ruby?

case x
  when 1
    puts "One"
  when 2
    puts "Two"
  else
    puts "Other"
end
Acase x when 1 puts "One" when 2 puts "Two" else puts "Other" end
Bcase x { when 1: puts "One" when 2: puts "Two" else: puts "Other" }
Cswitch(x) { case 1: puts "One" case 2: puts "Two" default: puts "Other" }
Dif x == 1 then puts "One" elsif x == 2 then puts "Two" else puts "Other" end
Step-by-Step Solution
Solution:
  1. Step 1: Check Ruby case/when syntax

    Ruby uses case followed by when clauses and ends with end. No braces or colons are used.
  2. Step 2: Compare options

    case x when 1 puts "One" when 2 puts "Two" else puts "Other" end matches Ruby syntax exactly. Options B and C use braces and colons like other languages. if x == 1 then puts "One" elsif x == 2 then puts "Two" else puts "Other" end is an if/elsif, not case/when.
  3. Final Answer:

    case x when 1 puts "One" when 2 puts "Two" else puts "Other" end -> Option A
  4. Quick Check:

    Ruby case/when uses no braces or colons [OK]
Quick Trick: Ruby case/when uses no braces or colons, just end [OK]
Common Mistakes:
  • Using braces or colons like other languages
  • Confusing case/when with switch/case from other languages
  • Using if/elsif instead of case/when

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes