From: John Joyce Date: 2007-12-02T03:21:14+09:00 Subject: Re: question about iterator On Dec 1, 2007, at 11:58 AM, Todd Benson wrote: > On Dec 1, 2007 10:08 AM, Paul Private wrote: >> david thanks for your help >> I have another question here perhaps you can help me out here >> normally when you do a sort it's working like this >> >> cursus =["java", "cobalt","php","ruby"] >> x=cursus.sort >> puts x >> >> this is working like a charm but when I try to implement this in the >> code mentioned earlier I get a error message like this >> oefeningen/_cursus_applic.rb:20:in `sort': undefined method `<=>' for >> # (NoMethodError) >> from oefeningen/_cursus_applic.rb:20 >> >> how can I solve this one? >> thanks for your help > > Ruby doesn't know how to compare Cursus objects. You must tell it how > by defining a <=> method, or you can use the #sort_by method with > something that understands <=> (like a string). > > If you are simply sorting by alphabetical order of one attribute, then > here's a simple example... > > class Animal > attr_reader :name > def initialize name > @type = name > end > end > > names = %w| tiger bear monkey zebra giraffe | > zoo = [] > names.each { |n| zoo << Animal.new(n) } > > zoo.each { |a| puts a.name } > puts "\n------------\n" > zoo_in_order = zoo.sort_by{ |a| a.name } > zoo.each { |a| puts a.name } > > Todd > Even consider this, simply have class Cursus inherit from another class that already implements methods you need such as .sort Enumerable or Array might be convenient, but I didn't read all of your class Cursus closely... In defining your class it is easy to override any inherited method, and generally a lot less work to inherit than to create everything from nothing. Is het voor en hogeschool in het Nederlands? Polytechnische school?