if..elsif
There will no doubt be occasions when you will need to take multiple different actions based on several alternative conditions. One way of doing this is by evaluating one if condition followed by a series of other test conditions placed after the keyword elsif. The whole lot must then be terminated using the end keyword.
For example, here I am repeatedly taking input from a user inside a while loop. An if condition tests whether the user enters “q” (I’ve used chomp() to remove the carriage return from the input). If “q” is not entered, the first elsif condition tests whether the integer value of the input (input.to_i) is greater than 800; if this test fails, the next elsif condition tests whether it is less than or equal to 800:
if_elsif.rb ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access