Function Overloading? Functions with the same name but different params

I’m creating function x with 1 param, and I want to create function x with the same name with 2 params, however defining x twice (but with different params) only has the second function defined, else Runtime Error - ArgumentError ... wrong number of arguments (given 1, expected 2)

My concrete usecase is creating a sample fader:

  times.times do
    sample sample
    amp -= ampFade
    sleep sleep
  end

but I also want to optionally pass in the starting amp and panning options, along with other params as it becomes more complex.

Currently I have to either create a new function whose name contains the additional params, ex. sample_fade_panning, or I have to call sample_fade with a bunch of nil, which is unintuitive because it requires looking up the function definition each time, and potentially passing in an almost full set of nills just to get the basic functionality.

I might be able to implement something by having a 1 param list passed into the function, but I’m not seeing the ability to pass in key:value pairings, which would allow me to identify the param names.

You can give default values to parameters, and then they become optional:

define :func do |a, b=42|
  print "func", a, b
end

func 1
func 1, 2

outputs:

{run: 1, time: 0.0}
 β”œβ”€ "func" 1 42
 └─ "func" 1 2

Thanks, this is somewhat useful. Is there a way to do named parameters within the function call? Otherwise your optionality is limited by your param ordering.

define :a do |b, c=1, d=2|
end

# a 1, d:2 
# a 1, d=2

I’ve tested both, and they don’t work.

Yes, this should do what you want:

define :func do |a, b: 0, c: 0|
  print "func", a, b, c
end

func 1
func 1, b: 2
func 1, c: 2

gives:

{run: 4, time: 0.0}
 β”œβ”€ "func" 1 0 0
 β”œβ”€ "func" 1 2 0
 └─ "func" 1 0 2
1 Like