How to operate rings, like insert/remove/append


#1

for a list I can use insert method to add items into it. how to do the same thing for a ring?


#2

Hi,

maybe this is what you are looking for:

It is part of the official tutorial so you should be able to open it from within Sonic Pi.

Martin


#3

(You can also access the tutorial online - so the above is also at http://sonic-pi.net/tutorial#section-8-5).


#4

Thanks! But I’ve checked out this tutorial before. What I want is something like:
r = (ring :e2)
r = r + :e3
puts r
// (ring :e2,:e3)

seems no solution in the tutorial?


#5

This might be what you are looking for

r = [:e2] #initialize r as an array
r.push(:e3) #push new value into array
puts r # prints [:e2, :e3]

The example below just shows that the array will run as a ring. If it was an array, it wouldn’t repeat the notes in the array.

live_loop :ringDemo do
  play r.ring.tick #runs through array as a ring
  sleep 1
end

Hope that helps. Just be aware that push is part of Ruby, not Sonic PI, so there is always a chance it might not work at some point.


#6

Yes! That exactly is what I am looking for ~ Thanks:)


#7

Hi there,

it’s important to point out that Sonic Pi’s rings are immutable. This means that you can’t change them in any way - which makes them safe to share across threads and live loops :slight_smile:

You can read about the various operations you can perform on rings here: http://sonic-pi.net/tutorial.html#section-8-5 Note that you should always use a new variable to capture the new ring, as the original ring is never changed:

a = (ring 1, 2, 3)
b = a.reverse
# a is not changed!

However, as @mrbombmusic points out, you can use normal arrays which aren’t immutable (and are therefore not sensible to share across threads) and then convert them to a ring with .ring to give you the ring abilities.

Also, rings do support push:

a = (ring 1, 2, 3)
b = a.push 4
puts b #=> (ring 1, 2, 3, 4)
puts a #=> (ring 1, 2, 3)

Note that you have to assign the result of push to a new variable as this does not modify a, but produces a whole new ring :slight_smile:

Happy to answer any further questions you might have.