Open classes (reopening classes) in Ruby - Time & Space Complexity
When we reopen a class in Ruby to add or change methods, it's important to see how this affects the program's speed.
We want to know how the time to run the program changes as we add more code inside the reopened class.
Analyze the time complexity of reopening a class and adding a method that loops through an array.
class Calculator
def sum(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
end
class Calculator
def multiply(numbers)
product = 1
numbers.each do |num|
product *= num
end
product
end
end
This code reopens the Calculator class to add a multiply method that loops through an array.
Look at the loops inside each method.
- Primary operation: Looping through the array with
eachto process numbers. - How many times: Once for each element in the input array.
As the array gets bigger, the number of steps grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(n)
This means the time to run the method grows in a straight line as the input gets bigger.
[X] Wrong: "Reopening a class adds extra loops that multiply the time complexity."
[OK] Correct: Each method runs separately, so reopening a class doesn't multiply loops; it just adds new methods.
Understanding how reopening classes affects performance helps you write clear and efficient Ruby code, a skill that shows you know how to manage program behavior and speed.
What if the multiply method called the sum method inside its loop? How would the time complexity change?
Practice
reopen a class in Ruby?Solution
Step 1: Understand Ruby class behavior
In Ruby, classes are open, meaning you can write the class again to add or change methods.Step 2: Identify what reopening means
Reopening a class means modifying the existing class by adding or replacing methods without deleting it.Final Answer:
You write the class again to add or change methods without deleting the original. -> Option AQuick Check:
Reopen class = add/change methods anytime [OK]
- Thinking reopening creates a new separate class
- Assuming reopening deletes the old class
- Confusing reopening with copying a class
String class and add a method shout that returns the string in uppercase with exclamation?Solution
Step 1: Check class reopening syntax
To reopen a class, writeclass ClassNameagain and define methods inside.Step 2: Verify method definition and behavior
Methodshoutshould return uppercase string plus exclamation, soself.upcase + "!"is correct.Final Answer:
class String def shout self.upcase + "!" end end -> Option AQuick Check:
Reopen class + define method correctly = class String def shout self.upcase + "!" end end [OK]
- Defining method outside class
- Using destructive method like upcase! which changes string
- Not returning uppercase string with exclamation
class Array
def first_two
self[0..1]
end
end
arr = [10, 20, 30, 40]
puts arr.first_two.inspectSolution
Step 1: Understand method added to Array
The methodfirst_tworeturns elements at index 0 and 1 usingself[0..1].Step 2: Apply method on given array
Array is[10, 20, 30, 40], sofirst_tworeturns[10, 20].Final Answer:
[10, 20] -> Option BQuick Check:
Array slice 0..1 = first two elements [OK]
- Confusing index ranges and getting wrong slice
- Expecting single element instead of array
- Thinking method returns nil
Integer class to add a method double. What is wrong?class Integer
def double
self * 2
end
end
puts 5.double()Solution
Step 1: Check if reopening Integer is allowed
Ruby allows reopening built-in classes like Integer to add instance methods.Step 2: Verify method and usage
Methoddoublemultipliesselfby 2, and calling5.double()returns 10.Final Answer:
Nothing is wrong; it will print 10. -> Option CQuick Check:
Reopen Integer + instance method works = 10 output [OK]
- Thinking built-in classes cannot be reopened
- Confusing instance and class methods
- Assuming syntax error in multiplication
Hash class to add a method symbolize_keys that returns a new hash with all string keys converted to symbols. Which code correctly does this?Solution
Step 1: Understand the goal
We want a method that returns a new hash with string keys converted to symbols.Step 2: Check each option's correctness
class Hash def symbolize_keys each_with_object({}) do |(k, v), h| h[k.to_sym] = v end end end manually builds a new hash but misses handling non-string keys safely. class Hash def symbolize_keys map { |k, v| [k.to_sym, v] } end end returns an array, not a hash. class Hash def symbolize_keys keys.map(&:to_sym) end end returns only keys as symbols, not a hash. class Hash def symbolize_keys self.transform_keys(&:to_sym) end end usestransform_keys(&:to_sym), a built-in method that correctly returns a new hash with symbol keys.Final Answer:
class Hash def symbolize_keys self.transform_keys(&:to_sym) end end -> Option DQuick Check:
Use transform_keys(&:to_sym) for symbol keys [OK]
- Returning array instead of hash
- Not returning a new hash
- Ignoring keys that are not strings
Ready to prove it?
Pass the test and this pattern moves unknown
