From: Jason Creighton Date: 2003-08-07T11:44:29+09:00 Subject: Re: What's New and Shiny in Ruby 1.8.0? On Thu, 7 Aug 2003 02:26:35 +0900 Ian Macdonald wrote: > On Wed 06 Aug 2003 at 10:17:44 +0900, Harry Ohlsen wrote: > > > This would be particularly useful if the data items in the enumeration were > > instances of more complex objects. Then, you could do things like: > > > > sorted = people.sort_by { |p| [p.last_name, p.first_name, p.salary] } > > How does one use this with one's own objects, though? > > I just cooked up an example Person class to play with and then tried to > sort it as above: > > class Person > include Enumerable ^^^^^^^^^^^^^^^^^^ Person doesn't implement #each, why mixin Enumerable? > attr_accessor :first_name, :last_name, :age > > def initialize(f,l,a) > @first_name = f > @last_name = l > @age = a.to_i > end > end > > p [d, g, i, j, p, j2, j3].sort_by { |x| [x.last_name, x.first_name, x.age] } > > and I get: > > /sort_by:23: undefined method `[]' for # > (NoMethodError) > > I'm fine with implementing Person#[], but I can't imagine how it should > look. ~/prog/ruby$ ruby -v ruby 1.8.0 (2003-08-04) [i686-linux] ~/prog/ruby$ cat person.rb class Person attr_accessor :first_name, :last_name def initialize(f,l) @first_name = f @last_name = l end def inspect "#{@first_name} #{@last_name}" end end ary = [ Person.new("Joe", "Blow"), Person.new("John", "Doe"), Person.new("Bill", "Blow"), Person.new("Jane", "Doe") ] p ary.sort_by { |x| [x.last_name, x.first_name ] } ~/prog/ruby$ ruby person.rb [Bill Blow, Joe Blow, Jane Doe, John Doe] BTW, your original example worked fine on my version of Ruby. Another option, of course, is to implement <=> for Person like so (untested) class Person def <=>(other) [ @last_name, @first_name ] <=> [ other.last_name, other.first_name ] end end Jason Creighton