Bang methods (ending with !) in Ruby - Time & Space Complexity
We want to see how the time it takes to run bang methods changes as the input grows.
How does the cost of these methods grow when working with bigger data?
Analyze the time complexity of the following Ruby code using a bang method.
arr = [1, 2, 3, 4, 5]
arr.reverse!
puts arr
This code reverses the array arr in place using the bang method reverse!.
Look for loops or repeated steps inside the bang method.
- Primary operation: The method swaps elements to reverse the array.
- How many times: It swaps pairs of elements about half the array length times.
As the array gets bigger, the number of swaps grows roughly in proportion to its size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 5 swaps |
| 100 | About 50 swaps |
| 1000 | About 500 swaps |
Pattern observation: The work grows steadily as the array size grows, roughly doubling the work if the array size doubles.
Time Complexity: O(n)
This means the time to reverse the array grows in a straight line with the size of the array.
[X] Wrong: "Bang methods are always faster because they change data directly."
[OK] Correct: Bang methods change data in place but still do the same amount of work as their non-bang versions, so speed depends on the operation, not just the bang.
Understanding how bang methods work and their time cost helps you explain your code choices clearly and confidently in real projects.
"What if we used reverse without the bang instead? How would the time complexity change?"