Add Methods to Existing Ruby Classes

I was working on a kata from CodeWars that asks to implement a series of methods that involve working with arrays. This led me to discovered a feature from ruby language that impressed me: You can extend the functionality of an existing class! In other words, you can add methods to an existing class.

To extend the functionality of Array class with two methods that allows to get the odds and evens number within the array we can do:

class Array

  def even{|x| x % 2 == 0}

  def odd
    self.reject{|x| x % 2 != 0}


And now, the object from Array will have both methods:

> [1, 2, 3, 4, 5].even
=> [2, 4]
> [1, 2, 3, 4, 5].odd
=> [1, 3, 5]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: