Post

Ruby Mixin and monkey patching examples

Let’s explore a couple of solutions to dynamically add a split_by_half behaviour to an array object. The first technique is the mixin: it allows to add the method to a single array instance. The second one is called monkey patching, and adds the method directly to the Array class, adding this behaviour to every array instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
######### MIXIN

module SplittableArray
  def split_by_half
    middle = (self.size.to_f / 2).floor
    return [self[0..middle], self[middle+1..self.size]]
  end
end

some_array = [1, 2, 3, 4, 5]
some_array.extend SplittableArray
some_array.split_by_half # => [[1, 2, 3], [4, 5]]


######### MONKEY PATCH ARRAY

class Array
  def split_by_half
    middle = (self.size.to_f / 2).floor
    return [self[0..middle], self[middle+1..self.size]]
  end
end

another_array = [6, 7, 8, 9, 10]
another_array.split_by_half # => [[6, 7, 8], [9, 10]]
This post is licensed under CC BY 4.0 by the author.