From: Harry Ohlsen Date: 2003-08-07T05:19:32+09:00 Subject: Re: What's New and Shiny in Ruby 1.8.0? On Thu, 7 Aug 2003 03:26, Ian Macdonald wrote: > 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 > > 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 would guess that there's something in the code you didn't show (ie, that defines d, g, i, j, p, j2 and j3) that's causing this error message. Here's an example that works just fine ... ---------------------- class Person include Enumerable attr_accessor :first_name, :last_name, :age def initialize(l,f,a) @first_name = f @last_name = l @age = a.to_i end def to_s "{#{@last_name}, #{@first_name}, #{@age}}" end end a = Person.new("Wall", "Larry", 40) b = Person.new("Matsumoto", "Yukihiro", 20) c = Person.new("Van Rossum", "Guido", 30) puts [a, b, c].sort_by { |x| [x.last_name, x.first_name, x.age] }.join("\n") #=> {Matsumoto, Yukihiro, 20} {Van Rossum, Guido, 30} {Wall, Larry, 40} ---------------------------------------------------------- Please note that those fake ages aren't intended to be accurate :-).