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?
You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference).
Ruby | Set add() method The add is an inbuilt method in Ruby which adds an element to the set. It returns itself after addition. Parameters: The function takes the object to be added to the set. Return Value: It adds the object to the set and returns self.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With