Ruby Shorthands 101

Ruby “if” Statement Short Expression

Ruby Ternary Operator

In Ruby, a ternary operator is a more concise alternative to an if/else. It consists of a conditional, followed by ? and an expression to be evaluated if the conditional is true, and then : and an expression to evaluate if the conditional is false.

The Case Statement

The if/else statement is powerful, but we can get bogged down in ifs and elsifs if we have a lot of conditions to check. Thankfully, Ruby provides us with a concise alternative: the casestatement. The syntax looks like this:

Conditional Assignment

if we only want to assign a variable if it hasn’t already been assigned,For this, we can use the conditional assignment operator: ||=. It’s made up of the or (||) logical operator and the normal = assignment operator.

Short-Circuit Evaluation

Recall that we have the boolean operators and(&&) and or (||) in Ruby. The && operator only returns true when the expressions on both sides of the operator are true; || returns true when one or the other or both of the expressions involved are true.

Up the Down Staircase

If we know the range of numbers we’d like to include, we can use .upto and .downto. This is a much more Rubyist solution than trying to use a for loop that stops when a counter variable hits a certain value.

Proc Syntax

Procs are easy to define! You just call Proc.newand pass in the block you want to save. Here’s how we’d create a proc called cube that cubes a number (raises it to the third power):

  1. Procs are full-fledged objects, so they have all the powers and abilities of objects. (Blocks do not.)
  2. Unlike blocks, procs can be called over and over without rewriting them. This prevents you from having to retype the contents of your block every time you need to execute a particular bit of code.

The Ruby Lambda

Like procs, lambdas are objects. The similarities don’t stop there: with the exception of a bit of syntax and a few behavioral quirks, lambdas are identical to procs.



Software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store