Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

Ruby for Newbies: Conditional Statements and Loops

by
This post is part of a series called Ruby for Newbies.
Ruby for Newbies: Working with Classes
Ruby for Newbies: Iterators and Blocks

Ruby is a one of the most popular languages used on the web. We've started a new screencast series here on Nettuts+ that will introduce you to Ruby, as well as the great frameworks and tools that go along with Ruby development. In this chapter, we’ll be looking at how conditional statements and loops work in Ruby.


Catch Up


View Screencast

Click the HD button for a clearer picture.

Subscribe to our YouTube page to watch all of the video tutorials!


Conditional #1: If Statement

The if statement is one of the first types of branching you learn when programming. You can guess what it means: if this is true, do one thing; if it’s not, do something else. In Ruby, these are pretty easy to write:

name = "Andrew"

if name == "Andrew"
	puts "Hello Andrew"
end

if name == "Andrew"
	puts "Hello Andrew"
else
	puts "Hello someone else"
end</code>

After the keyword if, code in your conditional statement. After that comes the code to execute if the condition returns true. You close the statement with the end keyword. If you’d like, you can squeeze an else statement in there, which will predictably execute if the condition is false.

elsif

It’s not hard to check for multiple conditions. Just put as many elsif statements as you’d like between the if and else statements. Yes, that's elsif, a marriage of else and if.

order = { :size => "medium" }

def make_medium_cofee
	puts "making medium statement"
end

#assume other functions

if order[:size] == "small"
	make_small_coffee;
elsif order[:size] == "medium"
	make_medium_coffee;
elsif order[:size] == "large"
	make_large_coffee;
else
    make_coffee;
end</code>

As I mentioned, you can have as many elsif conditions and their corresponding code blocks as you want.

Statements vs. Expressions

Most programming languages make a distinction between statements and expressions. A statements is a code construct that doens’t evaluate to a certain value. An expression is a code construct does return a value. For example, calling a function is an expression, because it returns a value. However, an if statement is exactly that, a statement, because it does not return a value. This means that you can’t do this in your JavaScript:

message = if (someTruthyValue) {
		"this is true";
	} else {
		"this is false";
	}</code>

Obviously, you can’t do this because the if statement does not return a value that you can assign to message.

However, you can do this with Ruby, because statements are actually expressions, meaning they return a value. So we can do this

message = if order[:size] == "small"
        "making a small"
    elsif order[:size] == "medium"
        "making a medium"
    else
        "making coffee"
    end</code>

Whichever block of code is executed will become the value of message.

If as a Modifier

If you don’t have any elsif or else clauses, and your if statement has only one line, you can use it as a modifier to a “normal” line.

puts "making coffee" if customer.would_like_coffee?</code>

Conditional #2: Unless Statement

In most programming languages, we want to reverse the return of the conditional expression, we have to negate it, usually with the bang (!) operator.

engine_on = true

if !engine_on   # meaning "if not engine_on"
	puts "servicing engine"  #should not be put, because "not engine_on" is false
end</code>

However, Ruby has a really nice unless operator, that keeps us from having to do that, while giving us much more readable code:

unless engine_on  # "unless engine_on" is better than "if not engine_on"
	"servicing engine"
end</code>

Just like if, you can use unless as a modifier:

puts "servicing engine" unless engine_on</code>

Conditional #3: Case / When Statement

If you’ve got a lot of options to work through, using if/elsif/else might be somewhat wordy. Try the case statement.

hour = 15

case
when hour < 12
	puts "Good Morning"
when hour > 12 && hour < 17
	puts "Good Afternoon"
else
	puts "Good Evening"
end</code>

It’s kinda-sorta-maybe like a switch/case statement in JavaScript (or other languages), except that there’s no one variable you’re evaluating. Inside the case/end keywords, you can put as many when statements as you’d like. Follow that when by the conditional expression, and then the lines of code go after it. Just like the if statement, the case statement is really an expression, so you can assign it to an expression and capture a returned value.

hour = 15

message = case
    when hour < 12
        "Good Morning"
    when hour > 12 && hour < 17
        "Good Afternoon"
    else
        "Good Evening"
    end

puts message</code>

Breaking Up Expressions

If you’re familiar with JavaScript, you’ll know that the blocks of code in an if statement are surrounded by curly braces. We don’t do this in Ruby, so it may seem like Ruby is dependant on the whitespace. Nothing could be further from the truth (take that, pythonistas :)).

If we want write your statements as one-liners, have to separate the different parts of the statements … but how? Well, you can use semi-colons:

if name == "Andrew"; some_code;
else; some_code; end</code>

If you don’t like the look of that (which I don’t), you can put the keyword then between the conditional expressions and the line of code.

if name == "Andrew" then sode_code; end</code>

This also works for a case statement.

case
    when x > 20; puts "<20"
    when x < 20 then puts "<20"
end</code>

Loop #1: While Loop

So, those are conditional statements (I mean, expressions). How about loops? Let’s look at while loops first.

A while loop will continue to execute until the condition stated is false:

arr = ["John", "George", "Paul", "Ringo"]
i = 0

while arr[i]
    puts arr[i]
    i += 1
end</code>

Here we’re looping over an array; when arr[i] returns false (meaning there are no items left in the array), the loop will stop executing. Inside the loop, we print out the current item in the array, and them add one to our increment variable.

You can also use while as a modifier

arr = ["John", "George", "Paul", "Ringo"]
i = -1

puts arr[i += 1] while arr[i]</code>

Loop #2: Until Loop

Just like unless is the opposite of if, until is the opposite of while. It will continue to loop until the condition is true:

days_left = 7;

until days_left == 0
    puts "there are still #{days_left} in the week"
    days_left -= 1
end</code>

And of course, it’s a modifier, too.

days_left = 8

puts "there are still #{days_left -= 1} in the week" until days_left == 1</code>

Loop #3: For Loop

Yes, Ruby has a for loop. No, it’s not like the for loop in other languages. It acts like a foreach loop, for looping over the values in an array or hash:

arr = ["John", "George", "Paul", "Ringo"]

for item in arr
    puts item
end</code>

If you’re looping over a hash, you can use two variable names, one for the key and one for the value:

joe = { :name => "Joe", :age => 30, :job => "plumber" }

for key, val in joe
    puts "#{key} is #{val}"
end</code>

That’s it!

I hope you’re enjoying our Ruby for Newbies Screencast series. If there’s something you’d like to see, let me know in the comments! (And if you’re not watching the videos, you should be. There’s a screencast-only bonus at the end of each one.)

Advertisement