Ruby for Newbies: Conditional Statements and Loops


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"

if name == "Andrew"
	puts "Hello Andrew"
	puts "Hello someone else"

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.


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"

#assume other functions

if order[:size] == "small"
elsif order[:size] == "medium"
elsif order[:size] == "large"

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";

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"
        "making coffee"

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?

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

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"

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

puts "servicing engine" unless engine_on

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

when hour < 12
	puts "Good Morning"
when hour > 12 && hour < 17
	puts "Good Afternoon"
	puts "Good Evening"

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"
        "Good Evening"

puts message

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

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

This also works for a case statement.

    when x > 20; puts "<20"
    when x < 20 then puts "<20"

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

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]

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

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

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

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}"

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.)

Related Posts
  • Code
    Object-Oriented Programming in WordPress: Control Structures IWordpress oop
    WordPress is a powerful CMS that provides a flexible foundation on which to build both sites and applications. If you want to extend WordPress functionality, then you do so via plugins. Although there are a number of different ways to do that, this series has us taking a look at object-oriented programming specifically from the perspective of a beginner and in the context of WordPress.Read More…
  • Computer Skills
    App Training
    Writing Destinations for DropzoneDropzone400
    Dropzone is not just another FTP upload client, but a great utilities platform for processing files and text. Dropzone is a collection of destinations that can have two types of actions: drag and drop action and/or a click action. There are a lot of pre-programmed destinations to use, but you can also write your own destinations in Ruby!Read More…
  • Code
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Code
    Mobile Development
    C++ Succinctly: Pointers, References, and Const-CorrectnessPreview image@2x
    Even though the concept of a pointer is simple, many people struggle with this topic. A pointer is nothing more than a variable that holds a memory address. After reading this article, pointers and references should no longer have secrets for you.Read More…
  • Code
    JavaScript & AJAX
    Testing in Node.jsNodejs testing chai retina preview
    A test driven development cycle simplifies the thought process of writing code, makes it easier, and quicker in the long run. But just writing tests is not enough by itself, knowing the kinds of tests to write and how to structure code to conform to this pattern is what it's all about. In this article we will take a look at building a small app in Node.js following a TDD pattern.Read More…
  • Code
    How to Accept Payments With StripeCode
    Processing credit cards is unfortunately far more difficult than we might hope, as developers. Given that it’s such a common task, is it really necessary that we jump through countless hoops (surrounded by fire, of course) for the sole purpose of processing a payment? Merchants? Gateways? SSL? Security? Very quickly, a seemingly simple operation can become an overwhelmingly confusing and, more importantly, dangerous task. Any time that you find yourself handling a user’s sensitive data, you better be on your toes. Read More…