Method objects with method() in Ruby - Time & Space Complexity
We want to understand how the time needed to run code changes when we use method objects created by method() in Ruby.
Specifically, we ask: how does calling a method object repeatedly affect the total work done?
Analyze the time complexity of the following code snippet.
class Greeter
def greet(name)
"Hello, #{name}!"
end
end
g = Greeter.new
m = g.method(:greet)
names = ["Alice", "Bob", "Carol", "Dave"]
names.each do |n|
puts m.call(n)
end
This code creates a method object from an instance method and calls it for each name in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the method object
m.call(n)inside the loop. - How many times: Once for each element in the
namesarray.
Each time we add more names, the number of method calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The total work grows directly with the number of names.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the list of names gets bigger.
[X] Wrong: "Using a method object makes calling the method slower and more complex."
[OK] Correct: Creating a method object is a one-time setup, and calling it inside a loop is just like calling a normal method each time, so the overall time grows linearly with input size.
Understanding how method objects behave helps you explain how Ruby handles method calls and objects, showing you know both language features and performance basics.
What if we replaced the array iteration with recursion calling the method object? How would the time complexity change?