Using Ruby builtin clamp (and other hidden functions?)

Trying to clamp a number, I saw Ruby has a useful Comparable#clamp method to do common myFloat.clamp(0,1). type stuff
but in sonic Pi it broke with: " wrong number of arguments (given 2, expected 1)"

After some digging around I found this release note:

Numeric#clamp - max and minimum bound (will clamp self to a value <= other and >= -1*other.`

So I assume this hides the builtin `clamp.

While a [-x, x] binding range can be useful, its hardly the only usage for clamp (I tend to clamp on [0,1] a lot, but sometimes arbitrary values as well).

Is there a way to use the ruby builtin clamp method?

P.S. - On a side note, is there an API reference for all custom functions?
I know about the tutorial (Which is awesome!), but it doesn’t cover the finer details of function discoverability and usage, which often stump me as a developer new to Sonic Pi.
Even just a list of functions with param type expectations would help a bunch.

Thanks! :slight_smile:

Hi @SuperSpasm!

So I assume this hides the builtin `clamp.

Correct. As far as I can tell, it seems that this redefinition of the function is not actually used elsewhere in the codebase, and obviously not mentioned in the official docs either - perhaps it was one of those things that was built as a test or experiment but never completely finalised? Not sure.

As far as using the standard Ruby Comparable#clamp - I think at the moment the only way you might be able to get it working again is to monkey patch it back in on Numeric again :joy: - so something like this, either in your ~/.sonic-pi/config/init.rb file, a Sonic Pi buffer, or an external Ruby file that you load with something like run_file:

class ::Numeric
  def clamp(a, b)
   # ... redefine the function again to match the standard Ruby version

For all I know, there may be an easier way, but that’s how I would do it :slight_smile:

Regarding a custom function API reference - the only docs at the moment are those built into the app, in the tabs such as ‘Synths’, ‘Fx’, ‘Samples’ and ‘Lang’, plus a few here and there in the Tutorial such as some mentions of some functions to chain rings together in Chapter 8.5 etc.

However long it might take, my long-term goal is to continually improve the Documentation where possible, as I’m aware there is probably a bunch more we could do. Hopefully we can add more functions like that in at some point - it’s always worth having that discussion :slight_smile:

So, I was not convinced about the solution I suggested above after thinking about it for a little - and it turns out that there might be a slightly simpler way to get it working the way you want - use this instead:

class ::Numeric
  remove_method :clamp

Thanks Ruby! :wink:

1 Like

Thanks! Ill try that out

And yeah, I remembered the “lang” tab afterwards, which can be super useful. :slight_smile: