I have a new requirement on Array object. So I need to add my own method to built-in Array class.
How do I add a new method so that whatever Array object I create, it will also have my instance method?
I have a new requirement on Array object. So I need to add my own method to built-in Array class.
How do I add a new method so that whatever Array object I create, it will also have my instance method?
Use Ruby Open Classes:
class Array
def mymethod
#implementation
end
end
The other answers basically show you can add a method to the class by redefining the class, just to add to that, an example could be like this:
class Array
def third
size > 2 ? self[2] : nil
end
end
a = [1, 2, 3, 4, 5]
puts a.third