Adding additional methods in Ruby

Language: Ruby

Requirement: You want to write this:

2.weeks.ago

and have the date two weeks ago returned. With Ruby it’s easy. You can add any method you want to any object (including core objects like FixNum). Fun, huh?

require ‘date’
class Weeks
def initialize(number)
@number = number
end
def ago()
return Date.today – (@number * 7)
end
end
class Fixnum
def weeks
return Weeks.new(self)
end
end

About the Author

Christian husband, father, runner, software engineer