Why Enumerable is Ruby's most powerful module - Performance Analysis
When using Ruby's Enumerable module, it's important to understand how the time it takes to run methods grows as the data size grows.
We want to know how the number of steps changes when we use Enumerable methods on collections.
Analyze the time complexity of the following Ruby code using Enumerable.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = numbers.select { |n| n.even? }.map { |n| n * 2 }
puts result.inspect
This code selects even numbers from an array and then doubles each selected number.
Let's find the repeating steps in this code.
- Primary operation: Iterating over the array twice -- once for
selectand once formap. - How many times: Each method goes through all elements in the array, so about
ntimes each, wherenis the number of items.
As the list gets bigger, the work grows in a simple way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (two passes over 10 items) |
| 100 | About 200 (two passes over 100 items) |
| 1000 | About 2000 (two passes over 1000 items) |
Pattern observation: The total steps grow roughly in direct proportion to the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the list gets bigger.
[X] Wrong: "Using two Enumerable methods means the time grows like n squared because of two loops inside each other."
[OK] Correct: The two methods run one after another, not inside each other, so the time adds up linearly, not multiplies.
Understanding how Enumerable methods scale helps you write clear and efficient Ruby code, a skill valued in many coding challenges and real projects.
What if we combined the select and map into one each loop? How would the time complexity change?