A Little Bit of Logic
Let’s take another look at our first branching program, here. What if my wife came home, saw the program, tried it, and it didn’t tell her what a lovely name she had? I wouldn’t want her to flip out, so let’s rewrite it:
puts 'Hello, what\'s your name?' |
name = gets.chomp |
puts 'Hello, ' + name + '.' |
if name == 'Chris' |
puts 'What a lovely name!' |
else |
if name == 'Katy' |
puts 'What a lovely name!' |
end |
end |
<= | Hello, what's your name? |
=> | Katy |
<= | Hello, Katy. |
What a lovely name! |
Well, it works…but it isn’t a very pretty program. Why not? It just doesn’t feel right to me that the whole “Katy” chunk of code is not lined up with the “Chris” chunk of code. These are supposed to be totally equal and symmetrical ...
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.