When I have an array of objects (Thing's, say) with two properties (say
`name' and `amount') I want to be able to sort that array by either of
these properties, depending on circumstances (like the value of the
variable `order').
The script below is an example, and it works, but I don't like it.
I there a better way to do it, without an if..else construction?
For example, would it be possible to put several {|a,b|...} blocks for
the sort in a hash with keys telling what I want to sort on?
#!/usr/bin/ruby
class Thing
attr_reader :name,:amount
def initialize(name,amount)
@name,@amount = name,amount
end
def list
puts ['',@name,@amount].join("\t")
end
end
class Array
def byamount
self.sort { |a,b| a.amount <=> b.amount }
end
def byname
self.sort { |a,b| a.name <=> b.name }
end
end
arr = [
Thing.new('John',10),
Thing.new('Anny',20)
]
order = :byname
puts "sorted #{order}:"
if order == :byname
arr.sort { |a,b| a.name <=> b.name }.each { |a|
a.list
# much more code may occur here...
}
elsif order == :byamount
arr.sort { |a,b| a.amount <=> b.amount }.each { |a|
a.list
# much more code may occur here...
}
else
raise "illegal order"
end
···
--
Wybo