You can use a break
(1..10).to_a.each.with_index do |element, index|
puts "element #{element}, index: #{index}"
break if index == 3
end
Using catch and throw
Following a syntax like this
catch :label do
(1..10).to_a.each.with_index do |e, index|
throw :label if condition
end
end
Practical example
def my_method
result = []
catch :completed do
(1..10).to_a.each.with_index do |element, index|
result << element
throw :completed if index == 3
end
end
result
end
my_method
=> [1, 2, 3, 4]
Using Return
If you want to use return, it will stop the iterations but also the method itself, so be aware of that, and that remember that the return clause only works if it is contained in a method
def return_example
values = []
(1..10).to_a.each_with_index do |element, index|
values << element
return values if index == 3
end
end
return_example
=> [1, 2, 3, 4]