问题
What's the idiom in Ruby when you want to have a default argument to a function, but one that is dependent on another parameter / another variable? For example, in Python, an example is:
def insort_right(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]: hi = mid
else: lo = mid+1
a.insert(lo, x)
Here, if hi
is not supplied, it should be len(a)
. You can't do len(a)
in the default argument list, so you assign it a sentinel value, None, and check for that. What would the equivalent be in Ruby?
回答1:
def foo(a, l = a.size)
end
来源:https://stackoverflow.com/questions/3875943/ruby-default-argument-idiom