Bird
0
0

You want to create a predicate method valid_name? that returns true only if a string is not empty and contains only letters. Which implementation is correct?

hard📝 Application Q15 of 15
Ruby - Methods
You want to create a predicate method valid_name? that returns true only if a string is not empty and contains only letters. Which implementation is correct?
Adef valid_name?(name) name.nil? && name.match?(/[a-z]/) end
Bdef valid_name?(name) name.empty? || name.match?(/\d+/) end
Cdef valid_name?(name) name.length > 0 && name.include?(' ') end
Ddef valid_name?(name) !name.empty? && name.match?(/^[a-zA-Z]+$/) end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirements

    The method must return true only if the string is not empty and contains only letters.
  2. Step 2: Evaluate each option

    def valid_name?(name) !name.empty? && name.match?(/^[a-zA-Z]+$/) end checks that name is not empty and matches only letters using regex /^[a-zA-Z]+$/. This meets the requirements.
  3. Final Answer:

    def valid_name?(name) !name.empty? && name.match?(/^[a-zA-Z]+$/) end -> Option D
  4. Quick Check:

    Not empty and only letters = valid_name? true [OK]
Quick Trick: Use regex and empty? to validate strings in predicates [OK]
Common Mistakes:
  • Using || instead of && for conditions
  • Checking for digits instead of letters
  • Ignoring empty string check

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes