An existing Ruby class is never closed. You can constantly add methods to an existing class. This applies to all classes.

This can be done on classes you defined, but also on standard classes. Meaning you can add functionality to existing Ruby classes also.

Download Free Ruby Ebook

Example

Ruby open class

First define a class and create an object.

1
2
3
4
5
6
7
8
9
class Dog
def bark
puts 'Woof! Woof!'
end
end

# make an object
d = Dog.new()
d.bark

How? Open up a class definition for an existing class, add the new content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Dog
def bark
puts 'Woof! Woof!'
end
end

class Dog
def spin
puts 'spins'
end
end

# make an object
d = Dog.new()
d.bark
d.spin

The class is not redefined here. Instead it’s reopened, and the method is attached to it.

Overwrite methods

You can also overwrite an existing method. The latest method will always be the one used.

Using Ruby open classes can create strange bugs. In general you should always update the existing classes.