There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
Agree with a comment or answer? Like () to up-vote the contribution!
“? and :” can only return the value of an expression.
“? and :” cannot replace all if/else statements, only ones that return one value if a given condition is true and another otherwise.
I found the following example on Stack Overflow found here-
Their question is a lot like your question: How do you make a "multiline ternary expression’.
This solution was offered:
condition ? (expression1 line 1; expression1 line 2; expression1 line 3) : expression2
However, the following caution was repeated by multiple users:
You should keep in mind that this reduces readability of your code. You are probably better off using an if / else statement to improve readability.
I went to used the ternary operator in the exercise just to see what it looked like, and how it worked.
def withdraw(amount, pin_number)
pin_number == pin ?
(@balance -= amount;
puts “Withdrew #{amount}. New balance: $#{@balance}.”):
(puts pin_error)
end
I went and made the same method using an if/else statement just to see what the folks on Stack Overflow were talking about:
def withdraw(amount, pin_number)
if pin_number == pin
@balance -= amount
puts "Withdrew #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end
It does look a bit more straightforward with the if/else statement. I think the main difference is instead of using the symbols ? and : the words ‘if’ and ‘else’ are in their place. For me, this lends a lot to understanding the code more easily.