Order notes starting at C thru B rather than A thru G

Discussion in 'Ruby' started by Max Williams, Jan 6, 2009.

  1. Max Williams

    Max Williams Guest

    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
    --
    Posted via http://www.ruby-forum.com/.
    Max Williams, Jan 6, 2009
    #1
    1. Advertising

  2. 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
    <=>
    --
    Posted via http://www.ruby-forum.com/.
    Brian Candler, Jan 6, 2009
    #2
    1. Advertising

  3. Max Williams

    Max Williams Guest

    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!
    --
    Posted via http://www.ruby-forum.com/.
    Max Williams, Jan 6, 2009
    #3
  4. On 06.01.2009 12:17, Max Williams wrote:
    > 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!


    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

    --
    remember.guy do |as, often| as.you_can - without end
    Robert Klemme, Jan 6, 2009
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Punya Narra
    Replies:
    5
    Views:
    1,674
    Itai Raz
    Feb 17, 2004
  2. Bjorn Jensen
    Replies:
    0
    Views:
    1,171
    Bjorn Jensen
    Mar 22, 2005
  3. SteveM
    Replies:
    5
    Views:
    1,552
    Mark Rae [MVP]
    Aug 28, 2007
  4. harryos
    Replies:
    1
    Views:
    3,164
    Jan Thomä
    Nov 18, 2008
  5. THTB
    Replies:
    0
    Views:
    173
Loading...

Share This Page