0
0
Rubyprogramming~5 mins

Open classes (reopening classes) in Ruby

Choose your learning style9 modes available
Introduction

Open classes let you add or change methods in a class anytime. This helps you improve or fix code without starting over.

You want to add a new method to a built-in class like String or Array.
You need to fix or change behavior of a class from a library you use.
You want to add helper methods to your own classes after they are defined.
You want to customize how existing methods work without copying the whole class.
Syntax
Ruby
class ClassName
  # new or changed methods here
end

You just write the class name again to reopen it.

Methods inside will add to or replace existing ones.

Examples
Adds a new method shout to the built-in String class.
Ruby
class String
  def shout
    self.upcase + "!"
  end
end
Adds a method to get the first two elements of any array.
Ruby
class Array
  def first_two
    self[0, 2]
  end
end
Replaces the existing reverse method in String with a new one.
Ruby
class String
  def reverse
    "Oops!"
  end
end
Sample Program

This program reopens the String class to add a greet method. Then it calls this method on a string.

Ruby
class String
  def greet
    "Hello, " + self
  end
end

name = "Alice"
puts name.greet
OutputSuccess
Important Notes

Be careful when changing existing methods; it can confuse others reading your code.

Open classes are powerful but use them wisely to avoid unexpected bugs.

Summary

Open classes let you add or change methods anytime by writing the class again.

You can add new methods or replace old ones in built-in or your own classes.

This helps customize or fix behavior without rewriting the whole class.