Require_relative / require in sonic pi

I’m a newbie to sonic pi and ruby (though a seasoned programmer).
Does sonic pi support require_relative and require? Where do I put the files to make them easily loadable?
If I define a variable in a require file, is it visible in the project I’m working in?
Here’s the code I’ve been fooling around with, and I think it’ll be useful in multiple projects.


Useful constants and functions for beat subdivisions

whole = 1.0
half = 0.5
quarter = 0.25
eighth = 0.125
sixteenth = 0.0625
dotted = 1.5
triplet = 2.0 / 3

define :tuple do |howmany|
powersoftwo = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0]
numerator = howmany > 32 ? howmany : { |i| i <= howmany && i > howmany / 2}.first
numerator / howmany

##| puts tuple(4)

I too am new to Sonic Pi and Ruby, but certainly not a seasoned programmer. I can say that require does work in Sonic Pi, but cannot say if it is officially supported - require does not appear under Help/Lang. This thread is where I found out how to download and ‘install’ Ziffers, for example:

Then I just run

require "~/ziffers/ziffers.rb"

zplay "e 0 2 1 3 2 4 35"

and it works fine. Sadly I cannot answer your second more specific question re variables scope.


That library sounds pretty cool!
In what directory do you put the rb file so it can find it in ~/*.rb? Still unclear about file locations.

After downloading the zip I extracted it to my home directory on OSX (Users/myName/ziffers) and Sonic Pi ‘sees’ the required .rb file via ~/ziffers/ziffers.rb, but I guess using any valid full directory path would work too:

require "/Users/brendan/Documents/ziffers/pathTest.rb"

zplay "s 0 2 1 3 e 2 4 35"

ps, how are you enjoying Sonic Pi?


So ~ represents my user home directory. Thanks, that clears everything up.
I am loving sonic pi. Haven’t had this much fun with a new musical tool in ages.
And I really appreciate such a supportive community.

1 Like