Method naming conventions (? and ! suffixes) in Ruby - Time & Space Complexity
We want to understand how the use of method names ending with ? and ! affects the time it takes for Ruby programs to run.
Specifically, we ask: Does adding these suffixes change how long methods take to execute?
Analyze the time complexity of these Ruby methods with ? and ! suffixes.
def contains_digit?(str)
str.each_char.any? { |ch| ch =~ /\d/ }
end
def upcase!(str)
str.upcase!
end
The first method checks if a string has any digit. The second changes the string to uppercase in place.
Look at what repeats inside these methods.
- Primary operation: Iterating over each character in the string for
contains_digit?. - How many times: Once per character until a digit is found or the string ends.
- For
upcase!: The method modifies the string directly without explicit loops here, but internally it processes each character.
As the string gets longer, the time to check or modify it grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 character checks or changes |
| 100 | Up to 100 character checks or changes |
| 1000 | Up to 1000 character checks or changes |
Pattern observation: The work grows roughly in direct proportion to the string length.
Time Complexity: O(n)
This means the time to run these methods grows linearly with the size of the input string.
[X] Wrong: "Methods ending with ? or ! run faster or slower because of their names."
[OK] Correct: The suffixes are just naming conventions. They do not change how Ruby runs the code inside the method.
Understanding that method names with ? and ! are about meaning, not speed, helps you write clear code and explain your choices confidently.
"What if the contains_digit? method used a regular expression match on the whole string instead of checking each character? How would the time complexity change?"