问题
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?
回答1:
Use Ruby Open Classes:
class Array
def mymethod
#implementation
end
end
回答2:
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
来源:https://stackoverflow.com/questions/17858816/adding-a-new-method-to-the-array-class