Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, how do I skip a loop in a .each loop, similar to 'continue' [duplicate]

In Ruby, how do I skip a loop in a .each loop, similar to continue in other languages?

like image 924
Blankman Avatar asked Nov 19 '10 23:11

Blankman


People also ask

How do you skip a loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

How do you stop an infinite loop in Ruby?

This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.

What is the preferred way of iterating through a list of objects in Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.


1 Answers

Use next:

(1..10).each do |a|   next if a.even?   puts a end 

prints:

1 3    5 7 9 

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

like image 88
Jakub Hampl Avatar answered Oct 20 '22 21:10

Jakub Hampl