Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping the .each { } iteration early in Ruby

code:

 c = 0    items.each { |i|      puts i.to_s        # if c > 9 escape the each iteration early - and do not repeat      c++    }   

I want to grab the first 10 items then leave the "each" loop.

What do I replace the commented line with? is there a better approach? something more Ruby idiomatic?

like image 395
BuddyJoe Avatar asked Oct 14 '09 18:10

BuddyJoe


People also ask

How do you exit 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 exit a block in Ruby?

To break out from a ruby block simply use return keyword return if value.

How do you exit 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.


2 Answers

While the break solution works, I think a more functional approach really suits this problem. You want to take the first 10 elements and print them so try

items.take(10).each { |i| puts i.to_s } 
like image 178
nimrodm Avatar answered Sep 28 '22 05:09

nimrodm


There is no ++ operator in Ruby. It's also convention to use do and end for multi-line blocks. Modifying your solution yields:

c = 0   items.each do |i|     puts i.to_s       break if c > 9   c += 1  end 

Or also:

items.each_with_index do |i, c|     puts i.to_s       break if c > 9 end 

See each_with_index and also Programming Ruby Break, Redo, and Next.

Update: Chuck's answer with ranges is more Ruby-like, and nimrodm's answer using take is even better.

like image 24
Sarah Vessels Avatar answered Sep 28 '22 05:09

Sarah Vessels