DEV Community

wuletaw wonte
wuletaw wonte

Posted on

Open class

Do you wonder what would happen to a code in a class definition in Ruby? For example, what would be the output of the following code?

class Movie
  puts "Hello there"
end

# Output
Hello there
Enter fullscreen mode Exit fullscreen mode

One may think because the “puts” code is outside any method, so it wont get executed. But the fact is, in Ruby, there is no real distinction between code that defines a class and code of any other kind. You can put any code you want in a class definition and its going to get executed. Here is another example

3.times do
  class Movie
    puts "Movie class"
  end
end

# Output
Movie
Movie
Movie
Enter fullscreen mode Exit fullscreen mode

Open Class in Ruby is the technique where you can define a class again to add or overwrite its methods dynamically at runtime. That means if you write a code that defines an already existing class Ruby would reopen the existing class and modify it. It is sometimes called Monkey Patching.

Ruby allows Monkey patching even on standard Ruby classes like String, Numeric or any other standard class. For example I can add palindrome method in the String ruby class to check if a string reads the same with its reverse.

class String
  def palindrome?
    self == self.reverse
  end
end

puts "wuletaw".palindrome? # false
puts "rotator".palindrome? # true
Enter fullscreen mode Exit fullscreen mode

As cool as this may seem, however, monkey patching does have a dark side. It can make code harder to maintain, introduce unexpected behavior and make it more difficult for other developers to understand.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more