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.
reopen a class in Ruby?String class and add a method shout that returns the string in uppercase with exclamation?class ClassName again and define methods inside.shout should return uppercase string plus exclamation, so self.upcase + "!" is correct.class Array
def first_two
self[0..1]
end
end
arr = [10, 20, 30, 40]
puts arr.first_two.inspectfirst_two returns elements at index 0 and 1 using self[0..1].[10, 20, 30, 40], so first_two returns [10, 20].Integer class to add a method double. What is wrong?class Integer
def double
self * 2
end
end
puts 5.double()double multiplies self by 2, and calling 5.double() returns 10.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?transform_keys(&:to_sym), a built-in method that correctly returns a new hash with symbol keys.Pass the test and this pattern moves unknown