The Ruby Workshop
上QQ阅读APP看书,第一时间看更新

Introduction

In the previous chapter, we studied the concept of arrays and hashes in Ruby. We also looked at different methods applied to arrays and hashes. In this chapter, we will be looking at how programs in Ruby are designed and used in applications.

Useful software programs are not simply a linear set of instructions; they make decisions about what code to run at any given time based on a set of conditions or criteria. Different programming languages have different types of program flow options. Two of the most common types of program flow options are conditionals and loops, which we will cover in this chapter.

Conditionals, also known as branches, are like a fork in the road. Do you turn left, or do you turn right? In the case of programming, for instance, you can decide what to do if a variable equals a value or is less than or greater than a certain value. Software simplifies the problem and makes the decision simply about truthiness: whether a condition is satisfied or not. A common example is evaluating a user's password and logging them in if the user-supplied value matches the value in the database or showing an error message if it does not.

Loops are another way to control program flow. A section of code will be repeated in a loop until a condition is met. In programming, you often want to loop over a collection of data such as an array and process the values in that collection. In some cases, the condition may never be met as the program may be configured to run forever. A web server, for instance, loops forever, waiting for new requests to come in to serve content.

In all types of program flow decisions, the fundamental unit is the Boolean. The Boolean represents truthiness or true or false values. We use the word "truthiness" to express that some values may not be an exact true or false Boolean but will be considered by the language as behaving as "true" or "false".

Since program flow is decided by truthiness, which is represented by Booleans, we need to learn how Booleans operate. We can do this by first learning about Boolean operators; there are three: AND, OR, and NOT. This is how we will begin our chapter.