Hint: empty? returns true only for empty strings [OK]
Common Mistakes:
Assuming non-empty strings return true
Confusing empty? with nil? method
Ignoring the question mark in method names
4. Identify the error in this Ruby code:
def positive?(num)
if num > 0
true
else
false
end
end
puts positive?("5")
medium
A. ArgumentError because "5" is a string, not a number
B. SyntaxError due to missing end
C. No error, outputs true
D. Returns nil instead of true/false
Solution
Step 1: Analyze method input and comparison
The method compares num > 0, but "5" is a string, not a number.
Step 2: Understand Ruby type comparison
Comparing string "5" with integer 0 causes an ArgumentError at runtime.
Final Answer:
ArgumentError because "5" is a string, not a number -> Option A
Quick Check:
Comparing string and integer causes ArgumentError [OK]
Hint: Check input types before numeric comparisons [OK]
Common Mistakes:
Passing strings instead of numbers
Assuming no error on mixed type comparisons
Missing end keyword (not the case here)
5. 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
A. def valid_name?(name)
name.nil? && name.match?(/[a-z]/)
end
B. def valid_name?(name)
name.empty? || name.match?(/\d+/)
end
C. def valid_name?(name)
name.length > 0 && name.include?(' ')
end
D. def valid_name?(name)
!name.empty? && name.match?(/^[a-zA-Z]+$/)
end
Solution
Step 1: Understand the requirements
The method must return true only if the string is not empty and contains only letters.
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.
Final Answer:
def valid_name?(name)
!name.empty? && name.match?(/^[a-zA-Z]+$/)
end -> Option D
Quick Check:
Not empty and only letters = valid_name? true [OK]
Hint: 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.