Can I extend existing class with new method

Hello! Can I extend existing class with a new method - for example, can I add new method to the Int32, String, Array or Hash classes/structs? Thanks!

1 Like

Yes, however it’s not really extending as it happens with inheritance.

Classes/structs of the same name (when defined in multiple places) all get smooshed together, thus adding that custom method to the standard lib’s String class. Also check out which talks about redefining methods.

A simple example of this is the serialization stuff

Where it is adding a to_json method that details how to serialize that given type.


What exactly do you want to do, what’s your usecase?

Reopening classes and redefining methods is a delicate matter. There are often better solutions.

Solved by @Blacksmoke16 - I overlooked reopening classes. Sometimes is very useful to add methods to existing classes, imagine methods like “seconds” or serialization methods on the Int32 class (or another core classes). Solved, thanks!

Just to point out #seconds already exists on Int32. I gets inherited from Int.

Also unless you are wanting a new serialization method JSON/YAML are already supported in the stdlib.

1 Like