loops vs blocks

M

Mathew Cucuzella

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
 
B

Brian Candler

Mathew said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top