From: "David A. Black" Date: 2007-12-02T16:35:41+09:00 Subject: Re: question about iterator Hi -- On Sun, 2 Dec 2007, John Joyce wrote: > > 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. The problem, though, is that you don't need Cursus objects to know about sort; you need them to know about <=>. The object that needs to know about sort is the collection you're sorting, which is (in all likelihood) already an array. The objects inside the collection need to have the <=> method. David -- Upcoming training by David A. Black/Ruby Power and Light, LLC: * Intro to Rails, London, UK, December 3-6 (by Skills Matter) See http://www.rubypal.com for details and 2008 announcements!