Ruby Notes - Control Flow

I’m 4 weeks into my 25 hours a week of Ruby self-study (I work part time right now otherwise it’d be 40+ hours) and just completed Codecademy’s Ruby track. Finishing was great but I felt I’d only scratched the surface of Ruby and programming in general. To supplement my minimal Ruby knowledge I decided to begin additional research and create study notes and do practice problems for each topic covered by Codecadmny, such as control flow, arrays, blocks, etc. This has already proven a success as I’ve seen a marked difference in my confidence and coding ability after completing notes for Control Flow and Arrays.

Now I’ve decided to turn my notes and practice problems into blog posts because:

  1. Hopefully it will be helpful to other people learning Ruby
  2. It forces me to read through my notes and practice problems again
  3. It requires rewriting my notes in way that others can understand thus further driving the concepts home for me
  4. Hopefully I’ll get feedback on my notes and practice problems (hint hint)

Control Flow

Control flow allows you to control how your ruby script executes based on conditions. For example, if condition A is met then do B OR unless B happens do A.

If Statement

An if statement tells the program what to do if a condition is met. That is, if the conditional that comes after if is true then execute the following code. If it evaluates to false, it doesn’t execute.

Example 1 - If Statements
1
2
3
4
5
money = true

if money
  puts You have money.
end

This if statement is saying if the variable money is true, puts the message “You have money.” In this case if money were set to false, nothing will puts to the screen.

Example 2 - If Statements
1
2
3
if 2 < 3
  puts 2 is less than 3
end

Since 2 is less than 3 this if statement evaluates to true and thus puts’ “2 is less than 3”. If we had typed if 2 > 3, puts would not have been executed and ‘nil’ would have been returned because the if statement would have evaluated to false.

If/Else Statement

Adding an else into the if statement essentially creates a default i.e. in the event whatever comes after if is false then do this.

Example - If/Else Statement
1
2
3
4
5
6
7
password = 12345678

if  password.length >= 8
  puts your password is long enough
else
  puts your password is too short
end

If/Elsif/Else

Using an elsif allows for multiple conditions to be added to the if statement. In this way we can essentially add multiple if statements to check for many different possible conditions.

Example - If/Elsif/Else Statement
1
2
3
4
5
6
7
8
9
10
11
city = San Francisco

if city == New York
  puts Jets & Giants
elsif city == Denver
  puts Broncos
elsif city == San Francisco
  puts 49ers
else
  puts Hmm we dont know what NFL team that city has.
end

If the variable city is set to any of the cities in our If/Else statement, the program will puts what NFL team that city has. If city is not set to one of those cities then the program puts the default message, “Hmm we don’t know what NFL team that city has.”

Unless

Unless is the opposite of an if statement. An if statement only executes if the conditional is true, conversely unless only executes if the conditional is false. It’s good practice to use unless instead of using if != (if not equal to) since if != can be a bit confusing.

The following if statement can be replaced with an unless statement.

Example of Bad If Statement
1
2
3
4
5
6
puts "Give us a message."
message = gets.chomp

if message != “”
  puts #{message}
end

By using unless this piece of code becomes much more readable.

Example of When to Use Unless
1
2
3
4
5
6
puts "Give us a message."
message = gets.chomp

unless message.empty?
  puts "#{message}"
end

Another good use case for Unless is to use them in a single line like so:

Example 2 - When to Use Unless
1
2
3
4
5
milk = false

puts Were out of milk. unless milk

#=> We’re out of milk

Here we’re saying only puts we’re out of milk if the milk variable is set to false. Since in this case milk is set to false then the message would be shown to the screen.

One more example:

Example 3 - When to Use Unless
1
i += 1 unless i > 10

Here i is being increased by 1 unless it is more than 10.

Unless Best Practices

There are some best practices you should follow when using unless to ensure you don’t confuse people or yourself. These aren’t universal, especially considering the Codecademy section on control flow doesn’t follow all of them, but after doing some research I’ve found these best practices given several places such as Code School’s Ruby Code Bits course and a blog post on the 37Signals blog called “Making Sense with Ruby’s ‘Unless’”.

  1. Don’t use else with unless. Codeacademy does this in some of their examples with unless and they aren’t all that confusing but they aren’t that straightforward either. It’s probably better to use an if statement if you want to use else.
  2. Avoid using more than a single logical condition. For example, doing things like unless a && b can become confusing fast.
  3. No double negatives. Unless is already a negative so don’t add in a != to make it a double negative…that’s just bad english.

Inline Conditionals

As mentioned when discussing unless, sometimes it’s best to write an if or unless statement on 1 line. Here are some examples:

Multy Line If Statement
1
2
3
if zipcode < 5
  fail zipcode too short
end

Can become:

Single Line If Statement
1
fail zipcode too short if zipcode.length < 5

Some more examples:

Single Line If Statement
1
puts Input your name: if name.empty?
Single Line Unless Statement
1
puts fail no username set unless username

The Ruby Ternary Operator

The ternary operator is another way to write an if else statement. The word ternary means consisting of or involving three. The ruby ternary operator consists of the following 3 parts:

condition ? value if true : value if false

In this case the ? is analogous to the word THEN and the : is analogous to OR. What a ternary operator is saying is if the condition evaluates to true THEN return the value if true OR if the condition evaluates to false, output the value if false.

This may not make sense 100% but an example should shore that up.

Ternary Operator Example
1
2
3
milk = true

puts milk ? We have milk : We dont have milk

Here the ternary operator is saying if milk = true THEN puts “We have milk” OR if milk = false, puts “We don’t have milk.”

For simple if/else statements Ruby’s ternary operator can be a nice thing to use.

Case Statements

Sometimes using an if/else statement can be too wordy and that is when you need a case statement. Instead of saying if, elsif, else, you simply use when, which is saying, when the conditional is true, run this code.

Here’s an example:

Case statement example
1
2
3
4
5
6
7
8
9
10
11
12
animal = dog

case animal
when animal == cat
  puts Meow!
when animal == parrot
  puts Polly want a cracker!
when animal == dog
  puts Woof!
else
  puts What animal is that?
end

Further reading on sase statements try - How A Ruby Case Statement Works and What You Can Do With It

Copyright © 2015 - Kyle Doherty. Powered by Octopress