ruby默认参数成语

Cla*_*diu 10 ruby default idioms default-value

当你想要一个函数的默认参数,但是一个依赖于另一个参数/另一个变量的函数时,Ruby中的成语是什么?例如,在Python中,一个例子是:

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)
Run Code Online (Sandbox Code Playgroud)

在这里,如果hi没有提供,它应该是len(a).您不能len(a)在默认参数列表中执行,因此您为其分配了一个标记值None,并检查它.Ruby中的等价物是什么?

hor*_*guy 13

def foo(a, l = a.size)
end
Run Code Online (Sandbox Code Playgroud)

  • 必须来之前 (5认同)