Why :define macro?


Why do we have the :define macro, as in

define :whatever do |args|

etc ? Why not just define a function in the standard Ruby manner ie

def whatever(args)

seems to me to do exactly the same thing. What am I missing ?


Here are some quotes from Sam Aaron on the subjecgt of Ruby and Sonic-Pi, in answer to a query from someone who wanted to use classes with Sonic Pi last year.

Sonic Pi shouldn’t be confused with Ruby :slight_smile:

Although it’s built on top of Ruby, it isn’t Ruby. You therefore can’t expect it to behave 100% like Ruby. In fact, unless something in the documentation or tutorial, you shouldn’t rely on it being there or changing in the future.

One of the main deviations from Ruby is to eschew object orientation in favour of a more functional approach. Classes have therefore never been (and are likely never to be) directly supported in the language.

In the same spirit, you should steer clear of using def for functions - instead prefer define. Similarly instance variables such as @foo shouldn’t be used.

def does work, but there MAY be situations wher it may cuase difficulites.Using define incorporates defined functions in Sonic Pi in a way that is expected and fully catered for by the Sonic Pi code.
Sonic Pi itself is written in Ruby and DOES use classes, def statements, instance variables but that does not mean that they should be used when coding with Sonic Pi.
If things work for you that are not documented well and good, but better to stick to documented commands where you can.
Having said that, I use quite a lot of Ruby that is not documented per se in Sonic Pi, particularly with list handing methods and using hashes etc. Also I have used file handling functions to save program parameters for subsequent runs using JSON format files.

@samaaron may care to comment further


Using ‘def’ seems pretty consistent with a functional approach, so I will probably keep using it until it breaks for me :grinning: