当我运行此程序时
def tng(x)
tn =( x * (x+1) )/2
return tn
end
i = 0
while tng (i) <= 500
i += 1
end
puts i
它给了我错误"undefined method `+' for true:TrueClass (NoMethodError)"
。我想这意味着true
是tng(x)
函数的输入,但为什么会这样?
答案 0 :(得分:4)
在Ruby 中,括号前的空格非常重要。解析器对待
while tng (i) <= 500
为:
while tng((i) <= 500)
后者被评估为true
因此错误。
旁注:不使用return
作为方法中的最后一个语句,它会自动返回。另外,不要使用while
循环,使用迭代器[除非你完全理解为什么在这里使用泛型loop
]:
def tng(x)
(x * (x + 1)) / 2
end
1.upto(Float::INFINITY).each do |i|
break i unless tng(i) <= 500
end