Thursday, June 28, 2007

Ruby's module mixin

# All you have to do is write an iterator called each, which returns the elements of our collection in turn. Mix in Enumerable, and suddenly your class supports things such as map, include?, and find_all?. If the objects in your collection implement meaningful ordering semantics using the <=> method, you’ll also get methods such as min, max, and sort.


class A
include Comparable
include Enumerable
attr :n

def initialize(n)
@n = n
end

def each
(1..@n).each do |i|
yield i
end
end

def <=>(b)
self.n <=> b.n
end
end

a = A.new(3)
b = A.new(4)

m = a.map {|i| i.to_s + __LINE__.to_s}

p m

n = a > b

p n

No comments :