I am writing an implementation of a binary search tree and in doing this I need a method that splits an array in two.

I am unsure where it is appropriate to place this method. What I mean by "where to place" is if I am going to monkey patch the array class, create a class method belonging to Tree, create a global method or lastly do something else which I have not thought of.

Here is some code to further describe the alternatives I have thought of.

Alternative 1: Monkey patch

class Array
  def split

Alternative 2: Class method

class Tree
  def Tree.split(a)

Alternative 3: Global method

def Tree.split(a)

Where is it appropriate to place this method?

As always thanks in advance for answering my question


  • What's the intended programming language? – Martin K Jan 20 at 20:09
  • The intended language is Ruby – fossegrim Jan 20 at 21:17

Unfortunately, there is no one size fits all answer.

Monkey patching is not generally a good idea as it places logic in places people don't think to look, especially new people who are looking at the API docs and trying to figure out where the split method is. However, there could be a very good reason to do it. For example if you think you're going to use Array.split nearly everywhere.

Instance v.s. class method is just the same old question. Does the logic need members of the instance? If yes then it's an instance method, if no, then it's a class method.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.