Alex Rivera | Logout

ruby default argument idiom

Asked 2010-10-06T18:55:51.440
10

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?

Edit
Report

1 Answer

13
def foo(a, l = a.size)
end
answered 2010-10-06T19:04:51.007

Your Answer