I can't find any useful resources online that breaks down Ruby's different flow-control options.
Let's assume that I'm iterating over an array within in a method:
def a_method
things.each do |t|
# control options?
end
end
What are my different flow-control options here? How do they differ?
A control flow construct is a language feature which disrupts the normal progression to the next statement and conditionally or unconditionally branches to another location in source code.
There are three basic types of logic, or flow of control, known as: Sequence logic, or sequential flow. Selection logic, or conditional flow. Iteration logic, or repetitive flow.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. Similarly, in Ruby, the if-else statement is used to test the specified condition.
The control flow is the order in which the computer executes statements in a script. Code is run in order from the first line in the file to the last line, unless the computer runs across the (extremely frequent) structures that change the control flow, such as conditionals and loops.
retry
can be used inside a rescue block, to jump back into the begin block after the condition that caused the exception has been remedied. Inside a block it has the effect of jumping to the beginning of the yielding method. So inside each this means that retry will jump to the beginning of the loop.
return
will return from the method it's inside of - in this case from a_method
.
break
will return from the yielding method - in this case from each
(which would be different from returning from a_method
if something happened between the end of the each-block and the end of a_method
).
next
will return from the block and thus jump to the next item in things
.
redo
will jump to the beginning of the block and thus repeat the current iteration.
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