-
Book Overview & Buying
-
Table Of Contents
The Ruby Workshop
By :
Ternary means composed of three parts. In Ruby (and also in other programming languages), there is a common programming idiom called the ternary operator, which allows a quick if/else conditional to be put on one line by breaking it into three parts:
user_input = 'password' secret = 'password' user_has_access = user_input == secret ? true : false
The three parts are the condition (user_input == secret), the statement if true (true), and the statement if false (false). The three parts are separated first by a ? and secondly by a : notation.
While Ruby doesn't always require syntax such as parentheses, the preceding statement may be a bit hard to read unless you are very familiar with how Ruby handles the order of operations. Here is a clearer way of writing the preceding code:
user_has_access = (user_input == secret) ? true : false
The ternary operator is great for quick one-liners. However, if lots of complex logic is starting...
Change the font size
Change margin width
Change background colour