If - Else - Elsif - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

If - Else - Elsif

Comparison operators and the resulting booleans are prerequisites for using if, else, and elsif statements.

x = 7

if x == 7

puts "Winner winner chicken dinner!"

end

Winner winner chicken dinner!

We set variable x to equal 7. We then told ruby to puts Winner winner chicken dinner! if x was equal to 7. Try changing x to 21 and watch ruby do nothing when you run the file.

That's pretty neat. On this next one, we want ruby to do something when x isn't equal to our set number. Try these shoes on:

x = 9

if x == 7

puts "The shoe fits!"

else

puts "Doesn't fit. I look ridiculous."

end

Doesn't fit. I look ridiculous.

Suppose we wanted to know if the shoe was too big or too small. How can we do this? We use the sorcery of elsif. First, ensure we have enough mana to cast the spell. Looks like enough. Everyone ready. "Leeeeeroy Jenkins!":

x = 10

if x == 7

puts "The shoe fits!"

elsif x > 7

puts "I look like a clown in these!"

else

puts "Way too small."

end

I look like a clown in these!

Try making x equal seven and then something below seven to see the results.

Note: When x isn't equal to or greater than seven we can conclude that x must therefore be less than seven. So we type: else "Way too small."

Let's consolidate. We don't want to have to change all the 7's next year because our feet grew.

x = 8

y = 7

if x == y

puts "I look fabulous!"

elsif x < y

puts "Are these baby shoes?"

else

puts "These are Shaq's shoes aren't they?"

end

These are Shaq's shoes aren't they?"

That's a little dramatic for only being off by one size. Let's add some more elsif's to help give us an idea of how close we are to the right shoe size.

x = 8

y = 7

if x == y

puts "I look fabulous!"

elsif x == y - 1

puts "Just barely too small. Try one size up."

elsif x == y + 1

puts "A little big. Let's go one size down."

elsif x < y

puts "Are these baby shoes?"

else

puts "These are Shaq's shoes aren't they?"

end

A little big. Let's go one size down.

Play around with x. Make it 6 and see what's returned.

Can you see why using the variable y rather than an actual number is more effective? We only needed to change the y variable once. Whereas before we would've needed to change the number in four different places.