Control Flow in Ruby
Learn how to write more complex programs that can respond to user input.
StartKey Concepts
Review core concepts you need to learn to master this subject
elsif
Statements in Ruby
Ruby not Operator
Else statement in Ruby.
Comparison operators in Ruby.
Or operator in Ruby.
if
Statement in Ruby
And operator in Ruby.
Unless statement in Ruby.
elsif
Statements in Ruby
elsif
Statements in Ruby
print "enter a number: "
num = gets.chomp
num = num.to_i;
if num == 5
print "number is 5"
elsif num == 10
print "number is 10"
elsif num == 11
print "number is 11"
else
print "number is something other than 5, 10, or 11"
end
In Ruby, an elsif
statement can be placed between if
and else
statements. It allows us to check for additional conditions.
More than one elsif
can be placed between if
and else
.
Control Flow in Ruby
Lesson 1 of 2
- 1You may have noticed that the kinds of programs we’ve written so far in Ruby aren’t very flexible. Sure, they can take user input, but they always produce the same result based on that input; they …
- 6In Ruby, we assign values to variables using =, the assignment operator. But if we’ve already used = for assignment, how do we check to see if two things are equal? Well, we use ==, which is a …
- 7We can also check to see if one value is less than, less than or equal to, greater than, or greater than or equal to another. Those operators look like this: * Less than: * Greater than or equal…
- 8Great work so far! You know what they say: practice makes perfect. Let’s try a few more comparators to make sure you’ve got the hang of this.
- 12You can combine boolean operators in your expressions. Combinations like (x && (y || w)) && z are not only legal expressions, but are extremely useful tools for your programs. These expression ma…
- 13Great work! So far you’ve learned: * How to use if, else, and elsif * How to use comparators / relational operators like ==, !=, , and >= * How to use boolean / logical operators like &&, ||, and !
- 14All right! You’re all on your lonesome. (Well, not quite. We’ll just leave this example here.) a = 10 b = 11 if a < b print “a is less than b!” elsif b < a print “b is less than a!” else p…
- 16Now let’s review comparators / relational operators. We’ve turned the tables a bit! Remember, comparators need to compare two values to each other to result in true or false 10 > 8 # true 8 > 10 …
- 17Home stretch! Let’s go over boolean operators. ( 1 == 1 ) && ( 2 == 2 ) # true ( 1 == 2 ) || ( 2 == 2 ) # true !( false ) # true 1. With && both comparisons on the left and right must evaluate…