Forum: Ruby Order notes starting at C thru B rather than A thru G

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2009-01-06 12:05
Say i have a bunch of note objects, which have a 'name' string, eg 'A'
'B#', 'Cb', 'D' etc.

I want to order them starting at 'C' through to 'B' - what's a simple
way to do this?

thanks
max
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2009-01-06 12:15
Max Williams wrote:
> Say i have a bunch of note objects, which have a 'name' string, eg 'A'
> 'B#', 'Cb', 'D' etc.
>
> I want to order them starting at 'C' through to 'B' - what's a simple
> way to do this?

Define a <=> operator in your class.

class Note
  include Comparable
  def <=>(other)
    name <=> other.name   # modify this to give your desired ordering
  end
end

'include Comparable' also gives you <, >, <= and >= operators based on
<=>
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2009-01-06 12:17
Brian Candler wrote:

>
> Define a <=> operator in your class.
>
> class Note
>   include Comparable
>   def <=>(other)
>     name <=> other.name   # modify this to give your desired ordering
>   end
> end
>
> 'include Comparable' also gives you <, >, <= and >= operators based on
> <=>

thanks!
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-01-06 13:42
(Received via mailing list)
On 06.01.2009 12:17, Max Williams wrote:
>>
>> 'include Comparable' also gives you <, >, <= and >= operators based on
>> <=>
>
> thanks!

An alternative approach is to do

notes.sort_by {|note| ... appropriate extraction here... }

or

notes.sort {|note_a, note_b| ... desired ordering code ... }

Cheers

  robert
This topic is locked and can not be replied to.