Ruby tip of the day (2)

Posted by phillip Sun, 12 Mar 2006 23:59:00 GMT

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

list = [,,

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.

Posted in , |