为什么下面的代码无法产生预期的输出,对于前两个测试用例,如果我没有将“then”部分添加到'If?'中我设置了第二个变量“False”的默认值,我的印象是,在Ruby中,一个方法可能带有不确定数量的参数,并且在调用方法时缺少参数将回滚到使用默认值如果设置了方法内的那些参数。在Ruby中为什么If/Then逻辑写入没有If/Then结构失败?
def alphabetize(arr,rev=false)
arr.sort!
if rev == true
arr.reverse!
end
end
numbers = [1,9,2,1,10]
测试用例:
print alphabetize(numbers,false)
=begin
input: numbers,false
output: nil
expected output: 1,1,2,9,10
=end
print alphabetize(numbers)
=begin
input: numbers
output: nil
expected output 1,1,2,9,10
=end
print alphabetize(numbers,true)
=begin
input: numbers,true
output: 10,9,2,1,1
expected output: 10,9,2,1,1
=end
此代码产生预期的结果:
def alphabetize(arr,rev=false)
if rev == true
arr.sort!.reverse!
else
arr.sort!
end
end
numbers = [1,9,2,1,10]
如果是这种情况,最后的测试用例如何工作? – brooklynsweb
@brooklynsweb我已经添加了进一步的说明。让我知道它是否合理。 – phss
这个解释是有道理的,但后来我又写了一个例子,它的行为和我原本预期的一样。有什么不同? *不幸的是,评论字段没有代码格式选项;这里有一个pastebin:http://pastebin.com/NGYYpqjB。更新:换句话说,第二个测试用例没有返回'nil',它没有返回任何内容,因为如果'if'失败,没有定义动作。 – brooklynsweb