0
0
Rubyprogramming~5 mins

Method naming conventions (? and ! suffixes) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method naming conventions (? and ! suffixes)
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the string gets longer, the time to check or modify it grows.

Input Size (n)Approx. Operations
10Up to 10 character checks or changes
100Up to 100 character checks or changes
1000Up to 1000 character checks or changes

Pattern observation: The work grows roughly in direct proportion to the string length.

Final Time Complexity

Time Complexity: O(n)

This means the time to run these methods grows linearly with the size of the input string.

Common Mistake

[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.

Interview Connect

Understanding that method names with ? and ! are about meaning, not speed, helps you write clear code and explain your choices confidently.

Self-Check

"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?"