On Dec 1, 2007 10:08 AM, Paul Private <paulus4605 / gmail.com> 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
> #<Cursus:0x28b55f4> (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