6

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?

2
  • 1
    Google "ruby open classes" Commented Jul 25, 2013 at 13:04
  • 2
    It's called monkey patching and it's done all the time. There's nothing special about the core classes that prevents you from adding methods to them. Commented Jul 25, 2013 at 15:20

2 Answers 2

14

Use Ruby Open Classes:

class Array
  def mymethod
    #implementation
  end
end
Sign up to request clarification or add additional context in comments.

8 Comments

If I do that my previous array objects don't get built in methods??
They were objects of built-in Array and now became object of my new class called Array. So only method available to that object is the newly added instance method. For eg. uniq method is no longer working. When I do this object.methods all I see are my own module methods (where I defined the above class Array) and some methods of the module where the Array is originally defined. How do I get around?
@user2562153 It's not your new class. It's still the same Array class, with all build in Array methods.
obj.class => # Class: X::Y::Z::Array, obj.methods => # Methods: ["==", "===", "=~", "id", "send", "class", "clone", "cy_rel_require", "display", "dup", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "methods", "my_contains_all?", "nil?", "object_id", "private_methods", "protected_methods", "public_methods", "respond_to?", "send", "singleton_methods", "taint", "tainted?", "to_a", "to_s", ...
Then you're doing something wrong, but, because you have NOT included the code you're using in your question, we can't help fix it. That is why you have to include the code. This is a simple question and problem but YOU have to help us help you. As is, people will vote to close your question for lack of useful information.
|
9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.