Why functional patterns complement OOP in Ruby - Performance Analysis
We want to see how combining functional patterns with object-oriented programming affects how long code takes to run.
Specifically, we ask: How does adding functional style change the work done as input grows?
Analyze the time complexity of the following Ruby code mixing OOP and functional style.
class Calculator
def initialize(numbers)
@numbers = numbers
end
def sum_squares
@numbers.map { |n| n * n }.reduce(0, :+)
end
end
calc = Calculator.new([1, 2, 3, 4])
puts calc.sum_squares
This code defines a class holding numbers and uses functional methods to square and sum them.
Look for loops or repeated work inside the code.
- Primary operation: The
mapmethod loops over each number to square it. - Secondary operation: The
reducemethod loops again to add all squared numbers. - How many times: Each method loops once over all numbers, so two passes total.
As the list of numbers grows, the code does more work in two passes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 for map + 10 for reduce) |
| 100 | About 200 (100 + 100) |
| 1000 | About 2000 (1000 + 1000) |
Pattern observation: The work grows roughly twice as fast as the input size because of two passes.
Time Complexity: O(n)
This means the time to finish grows directly in proportion to how many numbers we have.
[X] Wrong: "Using two loops means the time complexity is squared, like O(n²)."
[OK] Correct: The loops run one after another, not inside each other, so their times add up, not multiply.
Understanding how functional methods work inside classes helps you explain clear, readable code that scales well.
What if we combined the map and reduce into a single loop? How would the time complexity change?