【问题标题】:ruby default argument idiomruby 默认参数成语
【发布时间】:2011-04-22 00:21:57
【问题描述】:

当你想要一个函数的默认参数但依赖于另一个参数/另一个变量时,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)

此处,如果未提供hi,则应为len(a)。你不能在默认参数列表中做len(a),所以你给它分配了一个标记值,None,并检查它。 Ruby 中的等价物是什么?

【问题讨论】:

    标签: ruby default default-value idioms


    【解决方案1】:
    def foo(a, l = a.size)
    end
    

    【讨论】:

    • 如果有循环会发生什么? def foo(a=b, b=a)。还是只能引用之前定义的变量?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2013-06-10
    • 2019-12-14
    相关资源
    最近更新 更多