我有一个非常简单的代码问题:
def cond(x,y)
if x =~ /#{y}/
puts "ok"
else
puts "not ok"
break
end
end
result = `ls /path/to/some/file | grep something`
cond(result,"nothing")
我得到一个错误
Traceback (most recent call last):
./nodeexp.rb: ./nodeexp.rb:13: Invalid break (SyntaxError)
相同的代码,但没有在def中使用,工作正常:
result = `ls /path/to/some/file | grep something`
if result =~ /nothing/
puts "ok"
else
puts "nie ok"
break
end
我错过了什么?
1条答案
按热度按时间8wigbo561#
您遇到的错误是因为break语句在一个没有循环的方法(cond)中使用。在Ruby中,break语句通常用于退出循环(例如,while、for、each)。因为cond方法中没有循环,所以会得到一个SyntaxError。
在第一个代码片段中:
break语句没有一个循环可以中断,这就是为什么你会得到一个错误。
在第二个代码片段中:
它看起来工作得很好,因为它不在一个方法中,而你在一个if块中使用了break。但是,即使在这种情况下,使用break也是不合适的,因为break是用于在循环中过早退出循环的。它不应该在这种情况下使用。
如果你想退出一个脚本或终止一个程序,当一个条件不满足时,你可以简单地使用exit:
这将在满足“not ok”条件时退出脚本,而不需要循环或中断。