Ruby/Powrót do prostych przykładów: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Szymon wro (dyskusja | edycje)
Szymon wro (dyskusja | edycje)
Linia 122:
I rzeczywiście, możemy jesteśmy z tym bardziej ostrożni również w następnym skrypcie.
 
=== RegularWyrażenia expressionsregularne ===
 
W końcu zbadamy program z rozdziału o [[Ruby/Wyrażenia regularne|wyrażeniach regularnych]].
Finally we examine this program from the chapter on regular expressions.
 
<pre>
01 st = "\033[7m"
02 en = "\033[m"
Linia 139 ⟶ 140:
12 puts str.gsub(re, "#{st}\\&#{en}")
13 end
</pre>
 
W linii 6 w warunku dla pętli ''while'' zakodowany jest "na sztywno" wartość ''true'', co daje nam nieskończoną pętlę. Aby więc przerwać wykonywanie pętli umieściliśmy instrukcje ''break'' w liniach 8 i 10. Te dwie instrukcje są również przykładem "modyfikatorów ''if''". Modyfikator if wykonuje wyrażenie po swojej lewej stronie wtedy i tylko wtedy, gdy określony warunek jest prawdziwy. Konstrukcja ta jest niezwykła, gdyż działa logicznie od prawej do lewej strony, ale jest dostępna, ponieważ wielu ludziom przypomina ona podobne wzorce obecne w mowie potocznej. Dodatkowo jest ona zwięzła - nie potrzebuje wyrażenia ''end'' by wskazać interpretatorowi ile kodu następującego po ''if'' ma być traktowane jako warunek. Modyfikator ''if'' jest wygodnym sposobem używanym w sytuacjach, gdzie wyrażenie i warunek są wystarczająco krótkie by zmieścić się razem w jednej linii skryptu.
In line 6, the condition for while is hardwired to true, so it forms what looks like an infinite loop. However we put break statements in the 8th and 10th lines to escape the loop. These two breaks are also an example of "if modifiers." An if modifier executes the statement on its left hand side if and only if the specified condition is satisfied. This construction is unusual in that it operates logically from right to left, but it is provided because for many people it mimics a similar pattern in natural speech. It also has the advantage of brevity, as it needs no end statement to tell the interpreter how much of the following code is supposed to be conditional. An if modifier is conventionally used in situations where a statement and condition are short enough to fit comfortably together on one script line.
 
Note the difference in the user interface compared to the string-guessing script. This one lets the user quit by hitting the Return key on an empty line. We testing for emptiness of the input string, not for its nonexistence.