Ternary operator usage in Ruby - Time & Space Complexity
We want to see how using the ternary operator affects how long the code takes to run.
Does it change the speed depending on input size?
Analyze the time complexity of the following code snippet.
def check_number(num)
result = num > 0 ? "Positive" : "Non-positive"
result
end
check_number(5)
check_number(-3)
This code uses a ternary operator to decide if a number is positive or not.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison and assignment using the ternary operator.
- How many times: Runs once per function call, no loops or recursion inside.
Each time we call the function, it does one quick check, no matter the number size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations remains constant (1 check) regardless of the input size.
Time Complexity: O(1)
This means the operation takes the same small amount of time no matter what number you check.
[X] Wrong: "The ternary operator makes the code slower because it looks complicated."
[OK] Correct: The ternary operator is just a short way to write an if-else check. It runs just as fast as a simple if-else statement.
Understanding how simple operations like the ternary operator work helps you explain your code clearly and shows you know how code speed relates to what you write.
"What if we replaced the ternary operator with a loop that checks multiple numbers? How would the time complexity change?"