我对一段非常简单的代码有疑问:
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
我错过了什么?
您遇到的错误是因为在没有循环的方法(cond)中使用了break语句。在 Ruby 中,break 语句通常用于退出循环(例如 while、for、each)。由于 cond 方法中没有循环,因此您将收到 SyntaxError。
在第一个代码片段中:
def cond(x, y)
if x =~ /#{y}/
puts "ok"
else
puts "not ok"
break
end
end
break 语句没有可以跳出的循环,这就是您收到错误的原因。
在第二个代码片段中:
result = `ls /path/to/some/file | grep something`
if result =~ /nothing/
puts "ok"
else
puts "nie ok"
break
end
它看起来工作正常,因为它不在方法内部,并且您在 if 块内使用break。然而,即使在这种情况下,使用break也是不合适的,因为break旨在在循环内使用以过早退出循环。它不应该在这种情况下使用。
如果您想在不满足条件时退出脚本或终止程序,只需使用 exit:
result = `ls /path/to/some/file | grep something`
if result =~ /nothing/
puts "ok"
else
puts "not ok"
exit
end
当满足“不正常”条件时,这将退出脚本,而不需要循环或中断。