Bird
0
0

You want to categorize ages into groups using a Ruby case with ranges. Which code correctly assigns 'Child' for ages 0-12, 'Teen' for 13-19, and 'Adult' for 20 and above?

hard📝 Application Q8 of 15
Ruby - Control Flow
You want to categorize ages into groups using a Ruby case with ranges. Which code correctly assigns 'Child' for ages 0-12, 'Teen' for 13-19, and 'Adult' for 20 and above?
Aage = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20.. then puts 'Adult'\nend
Bage = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20..100 then puts 'Adult'\nend
Cage = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nelse puts 'Adult'\nend
Dage = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20-100 then puts 'Adult'\nend
Step-by-Step Solution
Solution:
  1. Step 1: Understand range patterns and else usage

    Ranges 0..12 and 13..19 cover child and teen. Adults are 20 and above, so else covers all >=20.
  2. Step 2: Evaluate each option

    age = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20.. then puts 'Adult'\nend uses 20.. which is invalid syntax. age = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20..100 then puts 'Adult'\nend uses 20..100 but excludes ages above 100. age = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nin 20-100 then puts 'Adult'\nend uses invalid 20-100. age = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nelse puts 'Adult'\nend uses else for adult, correctly covering all 20+ ages.
  3. Final Answer:

    age = 15\ncase age\nin 0..12 then puts 'Child'\nin 13..19 then puts 'Teen'\nelse puts 'Adult'\nend -> Option C
  4. Quick Check:

    Use else for open-ended ranges [OK]
Quick Trick: Use else for open-ended ranges in case [OK]
Common Mistakes:
  • Using invalid range syntax like 20..
  • Not covering all ages above 20
  • Using dash instead of two dots

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes