ruby default argument idiom

荒凉一梦 提交于 2020-01-02 01:19:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/3875943/ruby-default-argument-idiom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!