Loops vs blocks

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs