Branching
Branching is a simple concept, but it’s powerful. It’s how we tell Ruby to sometimes do this thing, and other times do that thing. Here’s what it looks like in code:
1: | puts "Hello, what's your name?" |
2: | name = gets.chomp |
3: | puts "Hello, #{name}." |
4: | |
5: | if name == "Chris" |
6: | puts "What a lovely name!" |
7: | 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’s branching. If what comes after the if keyword is true, you run the code between the if and the end. If what comes after the if keyword is false, you don’t. Plain and simple.
You may have noticed that the code is indented ...
Get Learn to Program, 3rd 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.