Ruby 101: How to add methods to a Ruby class

Let’s add a method that checks whether an Array has many elements.

  a = [1,2,3]
  a.many?  # NoMethodError: undefined method `many?'

Let’s fix this by adding a new method to the class Array.

  class Array
    def many?
      size > 1
  a = [1,2,3]
  a.many?   # true
  b = [1]
  b.many? # false
  c = []
  b.many? # false

Let’s implement Rails’ fancy ‘days.ago’ method:

  5.days.ago # NoMethodError: undefined method `days' for 3:Fixnum

Now, add the days and ago methods to Fixnum.

  class Fixnum
    def days
       self * 60 * 60 * 24   # we store seconds in a day
    def ago - self

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