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
    end
  end
  
  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
    end
  
    def ago
      Time.now - self
    end
  end

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