def one(a,b)
if a < 10
def two(b)
if b < 10
print "Both function failed"
else
print "ITs passed in second function TWO \n"
end
end
else
print "ITs passed in first function ONE \n"
end
end
one(11,10)
two(10)
上述程序的输出是
ITs passed in first function ONE
test2.rb:18:in `<main>': undefined method `two' for main:Object (NoMethodError)
我知道为什么会出现这个错误
test2.rb:18:in `<main>': undefined method `two' for main:Object (NoMethodError)
但如果功能失败则该怎么办
def one(a,b)
if a < 10
如果&lt; 10如果为真,我必须继续进行功能二
def one(a,b)
if a < 10
def two(b)
if b < 10
答案 0 :(得分:1)
不要在其他方法中定义方法。虽然Ruby在技术上允许它,但它会让人感到困惑,应该避免使用它。
在您的示例中,您运行one(11, 10)
。这将不执行if a < 10 ... end
分支,这意味着永远不会评估def two(b) ... end
。因此,未定义two
方法,因此NoMethodError
。
您应该将two
方法移到one
之外:
def one(a,b)
if a < 10
two(b)
else
print "ITs passed in first function ONE \n"
end
end
def two(b)
if b < 10
print "Both function failed"
else
print "ITs passed in second function TWO \n"
end
end
one(11,10) # ITs passed in first function ONE
two(10) # ITs passed in second function TWO