Initialize method as constructor in Ruby - Time & Space Complexity
We want to understand how the time it takes to create an object changes as we add more data inside it.
How does the constructor method's work grow when given more information?
Analyze the time complexity of the following code snippet.
class Person
def initialize(name, hobbies)
@name = name
@hobbies = hobbies
end
end
person = Person.new("Alice", ["reading", "swimming", "coding"])
This code creates a new Person object with a name and a list of hobbies.
Look for any repeated work inside the constructor.
- Primary operation: Assigning the list of hobbies to an instance variable.
- How many times: The assignment happens once, but the list size can vary.
The constructor sets the name and hobbies once each. The time to assign the hobbies depends on how many hobbies there are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 hobbies | About 1 assignment (the list reference) |
| 100 hobbies | About 1 assignment (the list reference) |
| 1000 hobbies | About 1 assignment (the list reference) |
Pattern observation: The work grows directly with the number of hobbies given only if the constructor processes the list; otherwise, it is constant time.
Time Complexity: O(1)
This means the time to create the object does not grow with the number of hobbies if it just assigns the list reference.
[X] Wrong: "The constructor always takes the same time no matter what."
[OK] Correct: If the constructor copies or processes a list, the time depends on the list size, so it grows as the list grows.
Understanding how constructors handle input size helps you explain object creation costs clearly and confidently in interviews.
"What if the constructor also loops through hobbies to print each one? How would the time complexity change?"
Practice
initialize method in a Ruby class?Solution
Step 1: Understand the role of
Theinitializeinitializemethod is called automatically when a new object is created.Step 2: Recognize what
It sets starting values for the object's instance variables, preparing the object for use.initializedoesFinal Answer:
It sets up initial values for a new object automatically. -> Option AQuick Check:
initializesets starting values [OK]
- Thinking initialize deletes objects
- Confusing initialize with printing methods
- Believing initialize defines class methods
initialize method in Ruby?Solution
Step 1: Check method naming conventions
Ruby requires the constructor method to be named exactlyinitializein lowercase.Step 2: Verify method syntax
def initialize(name) @name = name end correctly definesdef initialize(name)and assigns the instance variable@name.Final Answer:
def initialize(name)\n @name = name\nend -> Option AQuick Check:
Method name must beinitializelowercase [OK]
- Capitalizing 'Initialize' instead of 'initialize'
- Using wrong method syntax order
- Naming method 'init' instead of 'initialize'
class Person
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
p = Person.new("Alice")
puts p.greetSolution
Step 1: Understand object creation and initialization
ThePerson.new("Alice")callsinitializewith "Alice", setting@nameto "Alice".Step 2: Check the greet method output
Thegreetmethod returns "Hello, #{@name}!" which becomes "Hello, Alice!" when printed.Final Answer:
Hello, Alice! -> Option BQuick Check:
Instance variable set in initialize used in greet [OK]
- Expecting '@name' to print literally
- Forgetting to call greet method
- Confusing instance variable scope
class Car
def initialize(make, model)
make = make
model = model
end
end
car = Car.new("Toyota", "Corolla")
puts car.makeSolution
Step 1: Check variable assignment in initialize
The code assigns local variablesmake = makeandmodel = model, which do nothing to the object.Step 2: Correct usage of instance variables
To store values in the object, it should assign@make = makeand@model = model.Final Answer:
Instance variables are not assigned; should use @make and @model. -> Option DQuick Check:
Use @variable to store data in object [OK]
- Assigning to local variables instead of instance variables
- Thinking parameters auto become instance variables
- Wrong class naming conventions
Book that stores title and author when a new book is created. Which code correctly uses initialize to do this and allows reading these values later?Solution
Step 1: Check instance variable assignment
Three options assign@title = titleand@author = authorcorrectly ininitialize.Step 2: Verify how values are accessed
class Book attr_reader :title, :author def initialize(title, author) @title = title @author = author end end usesattr_readerto create getter methods for bothtitleandauthor, allowing easy access.Step 3: Identify issues in other options
class Book def initialize(title, author) title = title author = author end end does not assign instance variables, so values are lost. class Book def initialize(title, author) @title = title @author = author end def title title end end'stitlemethod returns local variabletitlewhich is undefined. class Book def initialize(title, author) @title = title @author = author end def get_title @title end end only provides a getter fortitle, notauthor.Final Answer:
class Book attr_reader :title, :author def initialize(title, author) @title = title @author = author end end -> Option CQuick Check:
Use attr_reader with instance variables for easy access [OK]
- Not assigning instance variables in initialize
- Returning undefined local variables in getter methods
- Missing getter methods for instance variables
Ready to prove it?
Pass the test and this pattern moves unknown
