Controlling the Flow of Logic
If, Else, While
ifstatement works as you’d expect, looking for a value it’ll see as
true. If you need the opposite effect, use the
unlessstatement instead. Shorter and easier to understand.
whilestatement has a similar counterpoint with the
- Simple logic statements, such as those assigning variables, can be collapsed into a single line. This saves space and is easier to understand.
If you need a simple “if, else” statement for something, use the ternary operator like so:
Case statements are good for more complex code reliant on, or assigning, a range of different values. These lines can also be collap
In Ruby boolean logic, only
nilare considered false values. Two things are false, everything else is true. So when testing for truth, don’t test for something to equal a specific value.
If you want to define a value to a variable but aren’t sure if it already has one, use this trick. If
@nameis nil or false, it’ll use the following string.