Wednesday, January 16, 2008

Add methods to an instance

list = ["first item", "second item", "third item"]

# Add some useful methods to list

class << list
def total
self.size
end
def second
self[1]
end
def third
self[2]
end
end

>> list.second
# "second item"
>> list.total
# 3
>> list.third
# "third item"
>> list.first
# "first item" (first is a pre-defined Array method)

No comments: