Sorting notes by name differs from sorting them by number

[:c2, :a3].sort returns [:a3, :c2] (high to low because of alphanumeric order. this is not what I would expect)
[:c2.to_i, :a3.to_i].sort returns [36, 57] (low to high because of numeric order. this seems right)

Is this intentional? I would expect notes to be sorted by frequency regardless of how they are specified.

Unfortunately this is intentional as :c2 is not a note, it’s a description of a note and given that Sonic Pi is built on top of a standard programming language (Ruby) it is sorted alphanumerically as you have observed.

I think the solution for this will be to introduce a new ring generator notes that converts all values within it to a MIDI number, then the following would work:

(notes :c2, :a3).sort #=> (ring 36, 57)

How does that sound?

Yes, I have a workaround and I think it is close to what you described:

define :sortNotes_LowToHigh do |notes|
  intNotes = []
  i = 0
  notes.length.times do
    intNotes[i] = notes[i].to_i
    i = i + 1
  end
  return intNotes.sort
end

Now I’m wondering… can I do this in a more elegant way? Like a lambda expression or something?

something like
return notes.each.to_i.collect
maybe?

This is how I’d do it :slight_smile:

define :notes do |*ns|
  ns.map{|n| note(n)}.ring
end

puts (notes :c3, :e2).sort #=> (ring 40, 48)

Oh this is beautiful!
Thank you!

1 Like