On 2003-08-09 16:47:10 +0900, Meino Christian Cramer wrote:
> But sort_by needs an array as input.
No, sort_by is a method of Enumerable and Enumerable is a mixin that can
be included in every class that implements the each method.
> Two questions:
> What I have to feed where into the structure to sort the broadcasters
> by frequency first and then by on-air-time ?
There are many possibilties. You could use sort_by as you said
(escpecially if you want to use a different order at different
occasions) or you could mixin Comparable into your Broadcaster class and
let the Broadcaster objects decide on their own how to compare to each
other.
> Is this "design" ok (in the sense of OOP)?
If you want to define one order that should be used for every
broadcaster, the Comparable version is more OOP because the Broadcaster
objects have the responsibility to compare to each other. If you want
more than one order it's perhaps better if the container class has that
responsibility.
class Broadcaster
include Comparable
def initialize(freq, station, time)
@freq, @station, @time = freq, station, time
end
attr_reader :freq, :station, :time
def <=>(other)
(self.freq <=> other.freq).nonzero? || other.time <=> self.time
end
def to_s
"<#@station: #@freq #@time>"
end
end
class List
include Enumerable
def initialize
@list = Array.new
end
def append(broadcaster)
@list.push(broadcaster)
end
def each(&block)
@list.each(&block)
end
end
alphabet = ("A".."Z").to_a
list = List.new
10.times do
list.append Broadcaster.new(
90.66 + rand(10),
(1..4).map { alphabet[rand(alphabet.size)] }.join,
rand(10000)
)
end
puts "sort_by:"
puts list.sort_by { |x| [ x.freq, -x.time ] }
puts "sort:"
puts list.sort
--
Programs must be written for people to read, and only incidentally for
machines to execute.
-- Abelson/Sussman, The Structure and Interpretation of Computer Programs