Ruby for Programmers – Part 4: Logic and Syntax

While everything in Ruby is in Object, the logic and syntax ties them all together.

This introduces some of the reserved words and their functions. As such, they are not objects but language structure:

nil/true/false

These are actually Objects, not unlike symbols.

And they work like you think they do. And you can negate truehood/falsehood with “!” such as “!variable” like in other languages too.

If/Unless/Elsif/Else

Hopefully you’re familiar with if statements. In Ruby, if statements can be run as a one-liner or inside a set of code:

Unless is the opposite of if, and can be considered a “not if” or “nif”, etc. Essentially “if true” is the same as “unless !true”. Also in Ruby a statement is always considered true unless it is nil or false.

If you need else, then it’s available before the end.

If you need an “else if”, then use the word “elsif”. Why “elsif”? I never found that answer.

Logic

Your usual “==”, “!=”, “>”, “>=”, “<", and "<=" works just fine in if statements:

Note that those statements are functions, and you could have fun with them if you feel like. Generally speaking, the function ">” is really just this: “<=>(2) == 1″ where the function <=> returns -1,0, or 1 depending on if it’s <, =, or >.

Case

Need a switch statement? It’s called ‘case’, and does some fancy stuff, like normal bunch of equals statements:

For numbers, in can accept a Range:

(Notice the else statement?) And can even check to see class membership:

Case is one of the few newline checking statements, the result ‘when’ statement must be on other lines or it must have a ‘then’ statement if on the same line. Weird, but whatever. (Also note that else doesn’t need or want the ‘then’ statement either.)

begin/rescue/ensure

Let’s say you’re trying to do something risky and causes an error:

Okay, so we can’t “+” a number with a string. Perhaps we can rescue from it?

Whoops, we goofed. Perhaps we can get more info on that?

So we can get a variable with information about the error itself.

One last thing, you can ensure the commands are run. Ensure is run regardless if an error occurs, it’s guaranteed to run. For example, you want to ensure a file is closed regardless of error:

So regardless of that error occurring, variable still was set to 10.