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

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

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

a =
b =

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

p m

n = a > b

p n

No comments :