Hello all,
I was thinking about this today. I'd like to be able to define
some "ways of sorting" objects (i.e., by different fields)
and just plug them in.
Passing a block to "sort" is neat, but it's a little more
intrusive than I have in mind.
I thought about a Proc object or something... but I ended
up doing it this way (see code below).
It works. But I'm sure many of you have better ideas.
How would *you* do it?
Hal
#########################
class Foo
attr_reader :str, :int, :chr
def initialize(str, int, chr)
@str, @int, @chr = str, int, chr
end
def inspect
"#@str #@int #@chr"
end
end
class Array
def sortBy(sym)
expr = sym.id2name + "(x,y)"
self.sort { |x,y| instance_eval(expr) }
end
end
def Str(x,y)
x.str <=> y.str
end
def Int(x,y)
x.int <=> y.int
end
def Chr(x,y)
x.chr <=> y.chr
end
x = [ Foo.new("abc", 237, ?a), Foo.new("xyz", 365, ?u),
Foo.new("dfg", 666, ?j), Foo.new("lkg", 111, ?i),
Foo.new("fkt", 999, ?s), Foo.new("krd", 123, ?t),
Foo.new("rej", 451, ?y), Foo.new("yhd", 555, ?k),
Foo.new("ajs", 143, ?l), Foo.new("jud", 199, ?f)]
a = x.sortBy :Str
b = x.sortBy :Int
c = x.sortBy :Chr
a.each { |x| p x }
puts "------"
b.each { |x| p x }
puts "------"
c.each { |x| p x }