In Ruby, a function can return multiple* values. Is it possible for a Ruby function to determine how many return values its invoking code is expecting?
For instance:
a = f() # caller expects one return value
a, b = f() # caller expects two return values
a, b, c = f() # caller expects three return values
If we let r be the number of expected return values, is it possible to write a function f such that it can find r?
Specifically, how could we change the definition of rcount, below, such that is passes the following tests:
a, b = rcount()
puts "#{a},#{b}" # FAIL, DESIRED: "2,1" ACTUAL: "1,"
a, b, c = rcount()
puts "#{a},#{b},#{c}" # FAIL, DESIRED: "3,2,1" ACTUAL: "1,,"
a, b, c, d = rcount()
puts "#{a},#{b},#{c},#{d}" # FAIL, DESIRED: "4,3,2,1" ACTUAL: "1,,,"
Where rcount is defined like this:
def rcount()
ret = []
r = nil # <== Q. IS IT POSSIBLE TO GET r PROGRAMMATICALLY?
r ||= 1
last = r - 1
(0..last).each do |i|
ret[i] = r - i
end
ret
end
*Actually multiple return values is syntactic sugar, the real return value is a single array. All Ruby functions return exactly one value.
No. The Ruby environment doesn’t give you that information. You could use an exception and ParseTree to find out what the calling code looks like, but that is overkill 🙂