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
Advertisement
Leave a Comment