Flow-control structures: Difference between revisions

add Ruby
m (→‎{{header|AWK}}: fixed italic markup)
(add Ruby)
Line 675:
...
1
 
=={{header|Ruby}}==
=== return ===
Return from the currently executing method to the caller.
=== loop control ===
Ruby's loop control statements are: <code>break, next, redo and retry</code>. Break and next are obvious. Redo and retry both restart the current loop iteration, but retry first reevaluates the condition.
They can control <code>while, until, for</code> loops and iterators.
=== exceptions ===
Use <code>raise</code> to throw an exception. You catch exceptions in the <code>rescue</code> clause of a <code>begin...end</code> block.
<lang ruby>begin
# some code that may raise an exception
rescue ExceptionClassA => a
# handle code
rescue ExceptionClassB, ExceptionClassC => b_or_c
# handle ...
rescue
# handle all other exceptions
else
# when no exception occurred, execute this code
ensure
# execute this code always
end</lang>
There is also a rescue modifier (example from the [http://www.pragprog.com/titles/ruby/programming-ruby Pickaxe book]):
<lang ruby>values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]</lang>
=== catch and throw ===
<code>break</code> will only break out of a single level of loop. You can surround code in a catch block, and within the block you can throw a string or symbol to jump out to the end of the catch block (Ruby's GOTO, I suppose):
<lang ruby>def some_method
# ...
if some_condition
throw :get_me_out_of_here
end
# ...
end
 
catch :get_me_out_of_here do
for ...
for ...
some_method
end
end
end
 
puts "continuing after catching the throw"</lang>
=== yield ===
<code>yield</code> passes control from the currently executing method to its code block.
 
=={{header|Tcl}}==
Anonymous user