Bird
Raised Fist0
Rubyprogramming~10 mins

Open classes (reopening classes) in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Open classes (reopening classes)
Define class
↓
Use class
↓
Reopen class
↓
Add/Change methods
↓
Use modified class
You first define a class, then later reopen it to add or change methods, and finally use the updated class.
Execution Sample
Ruby
class Dog
  def bark
    "Woof!"
  end
end

class Dog
  def wag_tail
    "Wagging tail"
  end
end

puts Dog.new.bark
puts Dog.new.wag_tail
This code defines a Dog class, then reopens it to add a new method wag_tail, and calls both methods.
Execution Table
StepActionEvaluationResult
1Define class Dog with method barkDog class created with bark methodDog#bark returns "Woof!"
2Reopen class Dog to add wag_tail methodDog class updatedDog#wag_tail returns "Wagging tail"
3Create Dog instance and call barkDog.new.bark"Woof!"
4Create Dog instance and call wag_tailDog.new.wag_tail"Wagging tail"
5End of programAll methods accessibleProgram ends successfully
💡 Program ends after calling both methods on Dog instances
Variable Tracker
VariableStartAfter Step 1After Step 2Final
Dog classundefinedDefined with bark methodReopened with wag_tail method addedHas bark and wag_tail methods
Key Moments - 2 Insights
Why can we define the Dog class twice without error?
In Ruby, reopening a class means the second definition adds to the existing class instead of replacing it, as shown in steps 1 and 2 of the execution_table.
Does reopening a class remove existing methods?
No, reopening a class adds or changes methods but keeps existing ones, so Dog has both bark and wag_tail after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does Dog#bark return at step 3?
A"Woof!"
B"Wagging tail"
CError: method not found
Dnil
💡 Hint
Check the Result column at step 3 in the execution_table.
At which step is the wag_tail method added to Dog?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the Action and Evaluation columns in the execution_table for when wag_tail is added.
If we removed the reopening of Dog class, what happens when calling wag_tail?
AReturns "Wagging tail"
BRaises NoMethodError
CReturns "Woof!"
DReturns nil
💡 Hint
Without reopening, wag_tail method does not exist; see variable_tracker and execution_table steps.
Concept Snapshot
Open classes in Ruby let you add or change methods anytime.
Define a class once, then reopen it later to add methods.
Existing methods stay unless explicitly changed.
Use reopened class normally with all methods available.
Full Transcript
This lesson shows how Ruby allows reopening classes to add or change methods after the initial definition. First, a Dog class is defined with a bark method. Then, the same Dog class is reopened to add a wag_tail method. Both methods can be called on Dog instances. The execution table traces each step: defining the class, reopening it, and calling methods. The variable tracker shows the Dog class gaining methods over time. Key moments clarify that reopening adds to the class without removing existing methods. The quiz tests understanding of method availability and behavior when reopening is omitted. This helps beginners see how Ruby classes are flexible and can grow over time.

Practice

(1/5)
1. What does it mean to reopen a class in Ruby?
easy
A. You write the class again to add or change methods without deleting the original.
B. You create a new class with the same name but different methods.
C. You delete the old class and replace it with a new one.
D. You make a copy of the class and modify the copy only.

Solution

  1. Step 1: Understand Ruby class behavior

    In Ruby, classes are open, meaning you can write the class again to add or change methods.
  2. Step 2: Identify what reopening means

    Reopening a class means modifying the existing class by adding or replacing methods without deleting it.
  3. Final Answer:

    You write the class again to add or change methods without deleting the original. -> Option A
  4. Quick Check:

    Reopen class = add/change methods anytime [OK]
Hint: Reopen means add or change methods by rewriting class [OK]
Common Mistakes:
  • Thinking reopening creates a new separate class
  • Assuming reopening deletes the old class
  • Confusing reopening with copying a class
2. Which of the following is the correct syntax to reopen the String class and add a method shout that returns the string in uppercase with exclamation?
easy
A. class String def shout self.upcase + "!" end end
B. def String.shout self.upcase + "!" end
C. class String def shout upcase! end end
D. class String def shout self + "!" end end

Solution

  1. Step 1: Check class reopening syntax

    To reopen a class, write class ClassName again and define methods inside.
  2. Step 2: Verify method definition and behavior

    Method shout should return uppercase string plus exclamation, so self.upcase + "!" is correct.
  3. Final Answer:

    class String def shout self.upcase + "!" end end -> Option A
  4. Quick Check:

    Reopen class + define method correctly = class String def shout self.upcase + "!" end end [OK]
Hint: Use class name again and define method inside [OK]
Common Mistakes:
  • Defining method outside class
  • Using destructive method like upcase! which changes string
  • Not returning uppercase string with exclamation
3. What will be the output of this Ruby code?
class Array
  def first_two
    self[0..1]
  end
end

arr = [10, 20, 30, 40]
puts arr.first_two.inspect
medium
A. [10]
B. [10, 20]
C. [20, 30]
D. nil

Solution

  1. Step 1: Understand method added to Array

    The method first_two returns elements at index 0 and 1 using self[0..1].
  2. Step 2: Apply method on given array

    Array is [10, 20, 30, 40], so first_two returns [10, 20].
  3. Final Answer:

    [10, 20] -> Option B
  4. Quick Check:

    Array slice 0..1 = first two elements [OK]
Hint: Slice array 0..1 to get first two elements [OK]
Common Mistakes:
  • Confusing index ranges and getting wrong slice
  • Expecting single element instead of array
  • Thinking method returns nil
4. This code tries to reopen the Integer class to add a method double. What is wrong?
class Integer
  def double
    self * 2
  end
end

puts 5.double()
medium
A. Method double should be defined as a class method, not instance method.
B. You cannot reopen built-in classes like Integer.
C. Nothing is wrong; it will print 10.
D. The method double uses wrong syntax for multiplication.

Solution

  1. Step 1: Check if reopening Integer is allowed

    Ruby allows reopening built-in classes like Integer to add instance methods.
  2. Step 2: Verify method and usage

    Method double multiplies self by 2, and calling 5.double() returns 10.
  3. Final Answer:

    Nothing is wrong; it will print 10. -> Option C
  4. Quick Check:

    Reopen Integer + instance method works = 10 output [OK]
Hint: Reopen built-in classes freely; instance methods work [OK]
Common Mistakes:
  • Thinking built-in classes cannot be reopened
  • Confusing instance and class methods
  • Assuming syntax error in multiplication
5. You want to reopen the 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?
hard
A. class Hash def symbolize_keys each_with_object({}) do |(k, v), h| h[k.to_sym] = v end end end
B. class Hash def symbolize_keys map { |k, v| [k.to_sym, v] } end end
C. class Hash def symbolize_keys keys.map(&:to_sym) end end
D. class Hash def symbolize_keys self.transform_keys(&:to_sym) end end

Solution

  1. Step 1: Understand the goal

    We want a method that returns a new hash with string keys converted to symbols.
  2. 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 uses transform_keys(&:to_sym), a built-in method that correctly returns a new hash with symbol keys.
  3. Final Answer:

    class Hash def symbolize_keys self.transform_keys(&:to_sym) end end -> Option D
  4. Quick Check:

    Use transform_keys(&:to_sym) for symbol keys [OK]
Hint: Use transform_keys(&:to_sym) to convert keys easily [OK]
Common Mistakes:
  • Returning array instead of hash
  • Not returning a new hash
  • Ignoring keys that are not strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard