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.
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
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define class Dog with method bark | Dog class created with bark method | Dog#bark returns "Woof!" |
| 2 | Reopen class Dog to add wag_tail method | Dog class updated | Dog#wag_tail returns "Wagging tail" |
| 3 | Create Dog instance and call bark | Dog.new.bark | "Woof!" |
| 4 | Create Dog instance and call wag_tail | Dog.new.wag_tail | "Wagging tail" |
| 5 | End of program | All methods accessible | Program ends successfully |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| Dog class | undefined | Defined with bark method | Reopened with wag_tail method added | Has bark and wag_tail methods |
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.