Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new method to the Array class

Tags:

ruby

instance

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?

like image 785
user2562153 Avatar asked Jul 25 '13 13:07

user2562153


People also ask

Can you put a method in an array?

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).

How do you add to a method in Ruby?

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.


2 Answers

Use Ruby Open Classes:

class Array
  def mymethod
    #implementation
  end
end
like image 159
Marek Lipka Avatar answered Oct 06 '22 00:10

Marek Lipka


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
like image 30
jsenk Avatar answered Oct 06 '22 00:10

jsenk