if statement supports else and elsif constructs in order to check the conditions in further level. some thing like below:
if customerName == "Fred" puts "Hello Fred!" elsif customerName == "John" puts "Hello John!" elsif customername == "Robert" puts "Hello Bob!" else puts "Hello Customer!" end
If any one of the above condition is true means, it will output the corresponding string. And nothing matched means, it will result the default output string Hello Customer!. So here we can check multiple condition using elsif.
elsif or elsunless constructs in unless statement:
But unfortunately unless statement supports only else construct not elsif or elseunless with in it. Lets walk through some example.
unless true puts "one" else puts "two" end #It will result the output as "two"
unless true puts "one" elsif true puts "two" else puts "three" end SyntaxError: compile error syntax error, unexpected kELSIF, expecting kEND
unless true puts "one" elseif true puts "two" else puts "three" end It wont throw any error, but will result the output as "three" instead of "two".
unless true puts "one" elsunless false puts "two" else puts "three" end Same like above it wont throw any error, but will result the output as "three" instead of "two".
What are the solutions to this:
Depending upon your condition, you need to select a appropriate if or unless statement.
Prefer if statement at first, then only unless statement.
If you need check multiple conditions then go only with if statement, cos in if statement only you can easily use multiple elsif constructs.
Use unless statement when you want to check a false output condition or a meaning full condition. For example, unless housefull print “Tickets are avilable” end
In Programmattic way:
Consider the following unless statement with elsif conditions can be modified into if..elsif statement.
unless true puts "one" elsif true puts "two" else puts "three" end #Above one will result error. Lets try to modify this statement in if..elsif statement as follows: unless true puts "one" else if true puts "two" else puts "three" end end