Ruby Conditionals - Else Clause
(Page 3 of 4 )
No, Else Clause is not the Swedish niece of old Saint Nick. In the above example, we found out what happened if the hammer_time conditional was met. But what if it wasn't hammer time? Aside from making Emanuelle Lewis very sad, what would happen?
hammer_time = 3
if hammer_time > 1 && hammer_time < 3
puts “Hammer Time!”
else
puts “Ice Ice Baby!”
end
Since the hammer_time value is greater than 1 but not less than 3 (remember, with the && operator both conditions must be met), the program outputs the following to the screen:
“Ice Ice Baby!”
Elseif
Elseif sounds like one of those words a little kid would say when they are angry. “Nu uh you better give me your ice cream elseif my big brother will beat you up!” That kid would grow up to be an awesome programmer, because he understands conditionals at such a young age.
Elseif clauses allow you to check for multiple conditions. Remember that insult program I used to make? Let's put it back in business...
my_name = “James”
if my_name == “James”
puts “You are so cool and handsome and have only one chin.”
elseif my_name == “Eric”
puts “Your fingers are so fat I'm surprised you can type.”
else
puts “I don't know that name, but you're probably an idiot.”
end
In the above example, my_name's value is “James”, so it would print out the text “You are so cool and handsome and have only one chin.” line. Had I made the value of my_name “Eric” it would have printed the line: “Your fingers are so fat I'm surprised you can type.” And finally, if I had changed the value of my_name to anything other than “James” or “Eric”, it would have printed: “I don't know that name, but you're probably an idiot.”
In simple terms, the program asks two questions. If the answer answers the first question, it performs one action, if not, it asks the second question. If the answer is the one it is seeking for the second question, it performs a different result. And finally, if the answer is not one the program is seeking for either question, it performs another result.
Next: Unless Statements >>
More Ruby-on-Rails Articles
More By James Payne