if, elsif and else
An if statement runs only the first branch whose condition is truthy, and because it is an expression it returns that branch's value, or nil if nothing ran.
Follow branch selection and use a conditional expression's resulting value.
Bean Cart's cup sizes cost different amounts: small, medium and large. The script has to pick one price out of three. if with elsif and else is how a Ruby program chooses a path, and in Ruby that choice is itself a value you can store.
The rule
The first true branch wins, and the whole
ifreturns its value.
The shape, with Ruby's unusual spelling elsif (no second "e"):
size = "medium"
if size == "small"
price = 3.50
elsif size == "medium"
price = 4.00
elsif size == "large"
price = 4.50
else
price = nil
endRuby checks the conditions from top to bottom and runs only the first branch whose condition is truthy. The rest are skipped, even if they would also be true. else catches everything that matched nothing. Every if closes with end. No parentheses are needed around the condition.
Because if is an expression, it returns the value of the branch that ran, so you can write the same thing without repeating price =:
price =
if size == "small" then 3.50
elsif size == "medium" then 4.00
else 4.50
end(then lets you put a branch on the same line as its condition.) If no branch runs and there is no else, the if returns nil.
Two compact forms are common for simple cases:
puts "Free cookie!" if total >= 10 # modifier if
label = total >= 5 ? "stamp" : "no stamp" # ternary: condition ? yes : noUse the modifier form when the action is short and the condition is the less important part. Use the ternary only for a simple choice between two values; nested ternaries are hard to read.