views:

65

answers:

1

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?

+4  A: 
def foo(a, l = a.size)
end
banister
what happens if you have a loop? `def foo(a=b, b=a)`. or can you only refer to vars defined before?
Claudiu
Must come before
banister