Using the ternary operator in Ruby
It’s been a little over a month at Flatiron School, and one of my biggest takeaways is refactor, refactor, refactor (only once you get your program working!). One operation I seem to use a lot is a simple if then like below
x = if a > 2
return "a is greater than 2"
return "a is less than or equal to 2"
Well it turns out there is something that can replace that style of code. The ternary operator, which Wikipedia which states it can be read as “if a then b otherwise c.” The code above can be simplified to
x = a > 2 ? "a is greater than 2": "a is less than or equal to 2"
So let’s break this down part by part.
First, you have your condition. In the example above, this is a > 2, but in reality it can be any condition.
After your condition, you put a question mark (?) and following that you put what happens if the condition is true.
Following your true value, you put a colon (:) and then your false value.
Complex ternary operations
You can actually nest ternary operators within each other. Is this a good thing? Probably not, but it’s possible. I found the code below on a random blog after typing in “complex ternary operations”
result = cost > 100 ? result = employed === "yes" ? "buy" : "cant afford" : "rejected cheap product"
Yikes. That one is probably better in a nested if statement. But I’ll let you be the judge :D
One thing to keep in mind, is that you can get a SyntaxError if any of your true / false values has spaces. If that’s the case, you need to surround your value within parenthesis.
x = y > 5 ? (puts "y is greater than 5") : (puts "y is less than 5")