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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.