Flow Control

Conditional Initialization

Initialize if there is not already a value

foo ||= "default" # => "default"
foo = "bar"
foo ||= "default" # => "bar"

Use and for nil safety

If the execution of a method relies on a condition then a useful shorthand is to.

foo = 2 > 1 && "wizz" # => wizz
bar = foo.is_a?(String) && foo.upcase # => WIZZ

Attach conditional to end of statement

foo = "bar"
"yey" if foo == "bar" # => "yey"

Using and and or

def legallyDrink?(age)
    age >=18
end

def inUK?(country)
    country == 'England' or
    country == 'Wales' or
    country == 'Scotland'
end

def drink
    puts "woo"
end

legallyDrink?(19) and inUK?("England") and drink # => woo!

Flow Example

$ ruby examples/flow-control.rb
initial
wizz
foo is actually wizz!
WIZZ
woo

Case Statement

Pretty much like most other languages

Rubyism:

def how_to_get_home(distance)
    case distance
    when "far away"
        "give up"
    when "close"
        "run"
    else
        "walk"
    end
end

Case Example

$ ruby examples/case.rb
give up

Loops

While

The following will output I'm bored once

i = 0;
devices = ['tv', 'kettle', 'fridge']
allConnected = false
while !allConnected
    connect(devices[i])
    sleep 1
    redo unless isConnected(devices[i])
    i += 1
    next unless i == 3
    break
end

While Example

$ ruby examples/while.rb
connecting tv
connecting kettle
connecting fridge

For

outputs the values from 1 to 10

for i in (1..10)
    puts i
end

TL;DR

Book

Pragmatic Ruby - expressions

Exercises

Ruby Monk - control structures

Videos

Ruby Fundamentals - flow control

Ruby Fundamentals - case statement

Ruby Fundamentals - case statement

Ruby Fundamentals - looping constructs

Challenge 🎠

Use Rspec to run the challenges

bin/rspec spec/challenges/flow-control_spec.rb --format doc

fix ../lib/challenges/flow-control.rb so the tests pass ✔️

Go to next challenge

Iterators and blocks