# Loops vs blocks

**URL:** <https://www.ruby-forum.com/t/loops-vs-blocks/173477>\
**Category:** Ruby\
**Created:** [August 10, 2009, 10:31am UTC](https://www.ruby-forum.com/t/loops-vs-blocks/173477 "2009-08-10T10:31:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kookjr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/df788c/32.png) [@kookjr](https://www.ruby-forum.com/u/kookjr)\
**Post date:** [August 10, 2009, 10:31am UTC](https://www.ruby-forum.com/t/loops-vs-blocks/173477/1 "2009-08-10T10:31:44Z")

</div>

It seems like the convention is to use blocks instead of more  
procedural loops. I’m really used to blocks now, but are there  
situations where a ‘for’ or ‘while’ loop is a more suitable  
choice?

The only situation where a ‘for’ loop seems more natural is when  
searching through an array, and you want to ‘break’ out when you find  
the element. Breaking out of a block doesn’t seem right, if it even  
works.

Thanks,  
-mat

---

<div class="post-metadata">

**Author:** ![kookjr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/df788c/32.png) [@kookjr](https://www.ruby-forum.com/u/kookjr)\
**Post date:** [August 10, 2009, 11:11am UTC](https://www.ruby-forum.com/t/loops-vs-blocks/173477/2 "2009-08-10T11:11:18Z")

</div>

Mathew C. wrote:

> The only situation where a ‘for’ loop seems more natural is when  
> searching through an array, and you want to ‘break’ out when you find  
> the element. Breaking out of a block doesn’t seem right, if it even  
> works.

Breaking out of a block _is_ the right thing to do. You can either use  
‘break’ just to break out of the block; ‘return’ to return from the  
enclosing method; or for more complex requirements there are catch and  
throw, although in practice those are almost never needed.

There are also predefined methods in Enumerable for searching through  
any enumerable object (such as an Array), e.g.

arr = [[“eggs”,4], [“beans”,15], [“cheese”,12]]  
p arr.find { |x,y| y \> 10 }

while or for loops are useful for iteration of indeterminite size, e.g.

while line = STDIN.gets  
… do stuff  
end

is probably clearer than

loop do  
break unless line = STDIN.gets  
… do stuff  
end

although in this particular case there is a natural iterator on STDIN  
anyway:

STDIN.each\_line do |line|  
… do stuff  
end
