Ruby函数未定义局部变量或方法

时间:2017-02-07 21:16:18

标签: ruby function

def mergesort(listin):
    listlen = len(listin)

    if listlen <= 1:
        return listin

    left = []
    right = []
    i = 0
    while i < listlen:
        if i <= listlen / 2:
            left.append(listin[i])
        else:
            right.append(listin[i])
        i += 1

    left = mergesort(left)
    right = mergesort(right)


    return merge(left, right)

def merge(listlef, listrig):
    result = []

    while len(listlef) != 0 and len(listrig) != 0:
        if listlef[0] <= listrig[0]:
            result.append(listlef[0])
            listlef = listlef[1:]
        else:
            result.append(listrig[0])
            listrig = listrig[1:]

    while len(listlef) != 0:
        result.append(listlef[0])
        listlef = listlef[1:]
    while len(listrig) != 0:
        result.append(listrig[0])
        listrig = listrig[1:]

    return result

输出:def wri(var) puts var end wri(hey) ':未定义的局部变量或方法main.rb:4:in

错误在哪里?

1 个答案:

答案 0 :(得分:3)

您将变量hey作为参数传递给方法wri()。您可能需要字符串'hey'

>def wri(var)
>  puts var
>end
>nil
>wri('hey')
hey
=> nil
>the_variable_hey = 'hey'
=> 'hey'
>wri(the_variable_hey)
hey
=> nil