I’m wondering if it is possible, and if so how, to return values from a defined function. I’ve trawled through the lang help and don’t see a return statement, nor do I see any examples from the tutorial that return a value, and yet it must be possible, since the built-in functions often seem to return values. How do I do this?
Yes function will return values. You don’t neccesarily have to express this explicitly
See the following examples
define :double do |n|
n = 2 * n
end
puts double 13 #gives 26
define :doubleWrong do |n|
result = 2*n
k = 33
end
puts doubleWrong 13 #=> 33 ie it shows the last evaluated expression value
define :doubleOK do |n|
result = 2*n
k = 33
return result #specifies the return value
end
puts doubleOK 13 #gives the correct result 26
So you may see defined functions with or without a return keyword, but both are possible.
EDIT
of course if the function plays something, then the “result” can be heard as it executes eg.
define :pscale do |scale|
play_pattern_timed scale,0.2, release: 0.5
end
pscale scale(:c4,:minor_pentatonic) #play the scale
pscale scale(:c4,:minor_pentatonic).reverse #play it in reverse
So, am I right in thinking then that if there isn’t an explicit return statement, the function returns the result of the last assignment?
Yes. If the return keyword is not included the last expression in the function is returned
Thank you. I think this info is not in the tutorial and might be included as part of the define section.