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

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