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.

Top comments (0)