else works when the requirement doesn't fit the if
elsif is like the next if. I think it can go on infinitely.
Now for an example using numbers instead of strings. This program asks for your coffee size and how much sugar. Too much sugar will get you a beating from the barista.
puts 'What size coffee would you like? S/M/L'
coffee_size = gets.chomp
if coffee_size.capitalize == 'S' || coffee_size.capitalize == 'M' || coffee_size.capitalize == 'L'
puts 'And how many teaspoons of sugar for that coffee?'
sugar_tsp = gets.chomp
if coffee_size.capitalize == 'S'
if sugar_tsp.to_i > 1
puts 'Sir! That is way too much sugar for a small coffee!'
else
puts 'You got it! Coming right up!'
end
elsif coffee_size.capitalize == 'M'
if sugar_tsp.to_i > 2
puts 'Sir! That is way too much sugar for a medium coffee!'
else
puts 'You got it! Coming right up!'
end
elsif coffee_size.capitalize == 'L'
if sugar_tsp.to_i > 5
puts 'Sir! That is way too much sugar for large coffee!'
else
puts 'You got it! Coming right up!'
end
end
else
puts 'I\'m sorry, but we don\'t offer that size.'
end
No comments:
Post a Comment