Bird
0
0

You have a list of names with inconsistent spacing and letter cases:

hard📝 Application Q15 of 15
Ruby - String Operations
You have a list of names with inconsistent spacing and letter cases:
names = ["  Alice", "BOB  ", "  cHaRlie  "]

Which Ruby code correctly cleans this list by removing spaces and making all names lowercase?
Aclean_names = names.map { |n| n.strip.downcase }
Bclean_names = names.map { |n| n.downcase.chomp }
Cclean_names = names.map { |n| n.strip.upcase }
Dclean_names = names.map { |n| n.downcase }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to remove spaces and convert all names to lowercase.
  2. Step 2: Check each option

    clean_names = names.map { |n| n.strip.downcase } uses strip then downcase, which removes spaces first, then lowercases. clean_names = names.map { |n| n.downcase.chomp } uses chomp after downcase, but chomp removes only trailing newlines, not spaces, so spaces remain. clean_names = names.map { |n| n.strip.upcase } uses upcase which is wrong. clean_names = names.map { |n| n.downcase } does not remove spaces.
  3. Step 3: Choose best practice

    The code that uses strip to remove whitespace and downcase to lowercase correctly cleans the names.
  4. Final Answer:

    clean_names = names.map { |n| n.strip.downcase } -> Option A
  5. Quick Check:

    strip then downcase cleans names correctly [OK]
Quick Trick: Strip spaces first, then change case for clean strings [OK]
Common Mistakes:
MISTAKES
  • Using upcase instead of downcase
  • Confusing chomp with strip
  • Forgetting to map over the list

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes