published over 3 years ago (13.03.2006 00:59)
Ruby tip of the day (2)
Comparing objects in Ruby
UPDATE: the title is a bit misleading, it should better be “sorting ruby objects” or something like that. the point is to show that ruby’s collections have several methods to compare their contents - and that the comparison rule can be given in a block.
you have a couple of objects in a collection. you want to find out which of the objects has the highest position.
class SomeFoo
attr_reader :age
def initialize(age)
@age = age
end
end
list = [
SomeFoo.new(45),
SomeFoo.new(18),
SomeFoo.new(29)
]
oldest_foo = list.max {|a,b| a.age <=> b.age}
puts oldest_foo.age
=> 45
of course this comparison works for anything you can write a block for.