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?
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.
To break out from a ruby block simply use return keyword return if value.
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.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With