Adding a new method to the Array class

落爺英雄遲暮 提交于 2019-12-12 10:54:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!