Branching

Branching is a simple concept, but it’s powerful. In fact, it’s so simple that I bet I don’t even have to explain it at all; I’ll just show you:

puts ​'Hello, what​\'​s your name?'
name = gets.chomp
puts ​'Hello, '​ + name + ​'.'
if​ name == ​'Chris'
puts ​'What a lovely name!'
end
<= Hello, what's your name?
=> Chris
<= Hello, Chris.
 What a lovely name!

But if we put in a different name…

<= Hello, what's your name?
=> Chewbacca
<= Hello, Chewbacca.

And that is branching. If what comes after the if is true, we run the code between the if and the end. If what comes after the if is false, we don’t. Plain and simple.

I indented the code between the if and the end just because I think it’s easier to keep track of the branching that ...

Get Learn to Program, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.