How to break out from a ruby block? Use the keyword next. If you do not want to continue to the next item, use break.
When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
1 2 3 4 | f.each do |line| # Iterate over the lines in file f next if line[0,1] == "#" # If this line is a comment, go to the next puts eval(line) end |
When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:
1 2 3 4 5 | f.each do |line| break if line == "quit\n" puts eval(line) end puts "Good bye" |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.