What is Ruby - Complexity Analysis
When learning Ruby, it helps to understand how the time a program takes can grow as it works with bigger data.
We want to see how Ruby code runs slower or faster when the input changes size.
Analyze the time complexity of the following code snippet.
def sum_array(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
arr = [1, 2, 3, 4, 5]
puts sum_array(arr)
This code adds up all the numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input.
[X] Wrong: "The time to add numbers stays the same no matter how many numbers there are."
[OK] Correct: Each number must be added one by one, so more numbers mean more work.
Understanding how Ruby code runs with bigger inputs helps you explain your thinking clearly and shows you know how to write efficient programs.
"What if we changed the array to a nested array and summed all numbers inside? How would the time complexity change?"