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

M

Max Williams

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
 
B

Brian Candler

Max said:
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
<=>
 
M

Max Williams

Brian said:
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!
 
R

Robert Klemme


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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top