红宝石默认参数成语 [英] ruby default argument idiom

查看:83
本文介绍了红宝石默认参数成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您想为函数提供默认参数,但又依赖于另一个参数/另一个变量时,Ruby中的惯用法是什么?例如,在Python中,示例为:

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)

此处,如果未提供 hi ,则应为 len(a)。您无法在默认参数列表中执行 len(a),因此您将其指定为前哨值,无,然后进行检查。

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?

推荐答案

def foo(a, l = a.size)
end

这篇关于红宝石默认参数成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆