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
    self.select{|x| x % 2 == 0}
  end

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

end

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]
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: