From: Toby DiPasquale Date: 2006-03-10T00:40:08+09:00 Subject: Re: nuby question: sorting with nils Farrel Lifson wrote: > Actually you can shorten it a bit further if you use > > @date ? @date <=> anItem.date : -1 > > That's due to the fact that in Ruby nil is equivalent to false in > conditional expression. Speaking of this very topic, I am having an issue where I want to sort objects by two of its attributes in a SortedSet, but its not working out: I'd like it to be sorted first by its :a attribute, but if they are equal, by whatever sorting on the :b attributes comes up with. Anybody know what I'm doing wrong in this test code? The third and fourth elements are not in the proper order (excuse the overly verbose <=> method... I was trying to get it working). puma:~> cat settest #!/usr/bin/env ruby X = Struct.new :a, :b class X def <=> other if not @a 1 elsif not @b -1 else if @a == other.a @b <=> other.b else @a <=> other.a end end end end require 'set' s = SortedSet.new s << X.new( 1, 2) s << X.new( 2, 1) s << X.new( 3, 3) s << X.new( 3, 4) s << X.new( 1, 2) p s x = X.new 3, 3 y = X.new 3, 4 p x <=> y p y <=> x p x <=> x puma:~> ./settest #, #, #, #}> 1 1 1 puma:~> -- Toby DiPasquale -- Posted via http://www.ruby-forum.com/.