Evgenii Legotckoi
June 25, 2016, 12:07 p.m.

User Guide #08 - Ruby - control structures

Content
  1. 1. case
  2. 2. while
  3. 3. for

This chapter explores more of ruby's control structures.

case

We use the case statement to test a sequence of conditions. This is superficially similar to switch in C and Java but is considerably more powerful, as we shall see.

  1. ruby> i=8
  2. ruby> case i
  3. | when 1, 2..5
  4. | print "1..5\n"
  5. | when 6..10
  6. | print "6..10\n"
  7. | end
  8. 6..10
  9. nil

2..5 is an expression which means the range between 2 and 5, inclusive. The following expression tests whether the value of i falls within that range:

  1. (2..5) === i

case nternally uses the relationship operator === to check for several conditions at a time. In keeping with ruby's object oriented nature, === is interpreted suitably for the object that appeared in the when condition. For example, the following code tests string equality in the first when, and regular expression matching in the second

  1. when
.

  1. ruby> case 'abcdef'
  2. | when 'aaa', 'bbb'
  3. | print "aaa or bbb\n"
  4. | when /def/
  5. | print "includes /def/\n"
  6. | end
  7. includes /def/
  8. nil

while

Ruby provides convenient ways to construct loops, although you will find in the next chapter that learning how to use iterators will make it unnecessary to write explicit loops very often.

A while is a repeated if. We used it in our word-guessing puzzle and in the regular expression programs (see the previous chapter ); there, it took the form while condition ... end surrounding a block of code to be repeated while condition was true. But while and if can as easily be applied to individual statements:

  1. ruby> i = 0
  2. 0
  3. ruby> print "It's zero.\n" if i==0
  4. It's zero.
  5. nil
  6. ruby> print "It's negative.\n" if i<0
  7. nil
  8. ruby> print "#{i+=1}\n" while i<3
  9. 1
  10. 2
  11. 3
  12. nil

Sometimes you want to negate a test condition. An unless is a negated if, and an until is a negated while. We'll leave it up to you to experiment with these.

There are four ways to interrupt the progress of a loop from inside. First, break means, as in C, to escape from the loop entirely. Second, next skips to the beginning of the next iteration of the loop (corresponding to C's continue). Third, ruby has redo, which restarts the current iteration. The following is C code illustrating the meanings of break, next

  1. ,
and redo:

  1. while (condition) {
  2. label_redo:
  3. goto label_next; /* ruby's "next" */
  4. goto label_break; /* ruby's "break" */
  5. goto label_redo; /* ruby's "redo" */
  6. ...
  7. ...
  8. label_next:
  9. }
  10. label_break:
  11. ...

The fourth way to get out of a loop from the inside is return. An evaluation of return causes escape not only from a loop but from the method that contains the loop. If an argument is given, it will be returned from the method call, otherwise nil is returned.

for

C programmers will be wondering by now how to make a "for" loop. Ruby's for is a little more interesting than you might expect. The loop below runs once for each element in the collection:

  1. for elt in collection
  2. ...
  3. end

The collection can be a range of values (this is what most people mean when they talk about a for loop):

  1. ruby> for num in (4..6)
  2. | print num,"\n"
  3. | end
  4. 4
  5. 5
  6. 6
  7. 4..6

It may also be some other kind of collection, such as an array:

  1. ruby> for elt in [100,-9.6,"pickle"]
  2. | print "#{elt}\t(#{elt.type})\n"
  3. | end
  4. 100 (Fixnum)
  5. -9.6 (Float)
  6. pickle (String)
  7. [100, -9.6, "pickle"]

But we're getting ahead of ourselves. for is really another way of writing each, which, it so happens, is our first example of an iterator. The following two forms are equivalen

  1. # If you're used to C or Java, you might prefer this.
  2. for i in collection
  3. ...
  4. end
  5.  
  6. # A Smalltalk programmer might prefer this.
  7. collection.each {|i|
  8. ...
  9. }

Iterators can often be substituted for conventional loops, and once you get used to them, they are generally easier to deal with. So let's move on and learn more about them.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…