Ruby Magic: Metaprogramming

Rails, if you’ve used it, has a rather elegant way of manipulating time. Stuff like 1.hours and 2.minutes.from_now just work. Let’s see how Ruby modules can be extended really really easily:

#! /usr/bin/env ruby

class Integer
  def seconds
    self
  end

  def minutes
    seconds * 60
  end

  def hours
    minutes * 60
  end

  def days
    hours * 24
  end

  def months
    days * 30
  end

  def years
    months * 12
  end

  def from_now
    Time.now + self
  end

  def before
    Time.now - self
  end
end

class String
  def palindrome?
    self == self.reverse
  end
end

class Time
  def leap_year?
    (year % 4).zero? and ((not (year % 100).zero?) or (year % 1000).zero?)
  end
end

class TrueClass
  def say
    "is"
  end
end

class FalseClass
  def say
    "is not"
  end
end

#2 is an Integer
puts 2.minutes.from_now

#"vishnu" is a String
puts "vishnu".palindrome?
puts "malayalam".palindrome?

puts 2.years.from_now.leap_year?

#Check if n years before is a leap year
puts "How many years before?"
year = Integer(readline)
puts "#{Time.now.year - year} #{year.years.before.leap_year?.say} a leap year."

The interesting thing about Ruby is not that metaprogramming is possible, but Ruby makes it really easy to do it.

One Reply to “Ruby Magic: Metaprogramming”

Leave a Comment

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