Evgenij LegotskojJune 25, 2016, 2:07 a.m.

User Guide #08 - Ruby - control structures

This chapter explores more of ruby's control structures.


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.

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

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:

(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 when .

ruby> case 'abcdef'
    | when 'aaa', 'bbb'
    |   print "aaa or bbb\n"
    | when /def/
    |   print "includes /def/\n"
    | end
includes /def/


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:

ruby> i = 0
ruby> print "It's zero.\n" if i==0
It's zero.
ruby> print "It's negative.\n" if i<0
ruby> print "#{i+=1}\n" while i<3

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 , and redo:

while (condition) {
   goto label_next;        /* ruby's "next" */
   goto label_break;       /* ruby's "break" */
   goto label_redo;        /* ruby's "redo" */

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.


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:

for elt in collection

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

ruby> for num in (4..6)
    |    print num,"\n"
    | end

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

ruby> for elt in [100,-9.6,"pickle"]
    |    print "#{elt}\t(#{elt.type})\n"
    | end
100    (Fixnum)
-9.6   (Float)
pickle (String)
   [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

#  If you're used to C or Java, you might prefer this.
for i in collection

#  A Smalltalk programmer might prefer this.
collection.each {|i|

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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting

C++ - Тест 003. Условия и циклы

  • Result:14points,
  • Rating points-10

C++ - Тест 003. Условия и циклы

  • Result:14points,
  • Rating points-10

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
Last comments
  • Andrey
  • April 28, 2021, 1:25 a.m.

Django - Tutorial 036. How to add authentication through social networks. VKontakte

после того как дам разрешение для просмотра моего емайл, вот такая ошибка: AuthForbidden at /social-auth/complete/vk-oauth2/ Your credentials aren't allowed Вот сетингс: SOC…

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Добрый вечер. Хотел бы получить консультацию по работе с проектом на Mac OS. Открыл проект в QT и собрал его. Проблема в том, что он не воспроизводит треки и их названия зацикленно мелькают в по…

Как соответствовать новым требованиям Google Play

Добрый день. Спасибо вам огромное за вашу статью! только начинаю изучать QT под Андроид 4 дня потратил на то чтобы подобрать версию QT которая наконец то скомпилирует мне на windo…

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Hello. Let's say I want to send some variables to "run" define. How can we do that? I modified your code, I tried something like below, but the GUI is frozen that way. I could not be able to und…

Распознавание изображений на Python с помощью TensorFlow и Keras

почему то вместо 50000 обрабатывает по 782 картинки кажду. эпоху
Now discuss on the forum

Потеря данных в сигнал/слот

вопрос решен

Qt/QML/Android(navigation button) - Стандартные клавиши навигации Андроид

Здравствуйте, пытаюсь заставить работать стандартную андроид-клавишу "назад", пытался разными способоами, они приведены в закомментированном коде. В том числе использовал https://evileg.com/ru/f…

Как включить OpenGL в Adnroid эмуляторе QtCreator

Здравствуйте, у меня работают виртуальные машины с Android, но только в дефолтной был включен OpenGL. Потом я удалил дефолтную, создал новые, а в них OpenGL отключен. Справа на втором скриншоте …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.

qml зажатая кнопка мыши в одной MouseArea и сигналы мыши из другой MouseArea

добрый, вы не пробовали отслеживать область видимости мышки через: _mouseArea.containsMouse и когда мышка будет в другой зоне видимости обрабатывать ее состояния?
© EVILEG 2015-2021
Recommend hosting TIMEWEB