Ruby - 意外返回(LocalJumpError)

时间:2016-08-11 01:36:14

标签: ruby

Ruby 2.0

为什么下面的代码会给出意外的返回(LocalJumpError)?

# some code here
puts "Scanning for xml files .."
zip_files = Dir.entries(directory).select { |f| File.extname(f) == '.zip' }
if(zip_files.count == 0)
    puts "No files found, exiting..."
    return
end
# more code here ( if files found)

Error: unexpected return (LocalJumpError)

No files found, exiting...
[Finished in 0.9s with exit code 1]

2 个答案:

答案 0 :(得分:6)

你不在某种方法中。你不能从那里return。如果您想提前退出,请使用exit

答案 1 :(得分:0)

或者,您可以营救LocalJumpError

puts "Scanning for xml files .."
zip_files = Dir.entries(directory).select { |f| File.extname(f) == '.zip' }

begin
  return unless zip_files.count > 0

  # more code here ( if files found)
rescue LocalJumpError
  puts "No files found, exiting..."
end