Ruby Idioms

Learn how to use common Ruby idioms.

We'll cover the following

A number of individual Ruby features can be combined in interesting ways. The meaning of such idiomatic usage is often not immediately obvious to people new to the language. We’ll use the following common Ruby idioms in this course:

Bang method and predicate method

Ruby method names can end with an exclamation mark (a bang method) or a question mark (a predicate method). Bang methods normally do something destructive to the receiver. Predicate methods return true or false, depending on some condition.

  • a || b

The expression a || b evaluates a. If it isn’t false or nil, the evaluation stops and the expression returns a. Otherwise, the statement returns b. This is a common way of returning a default value if the first value hasn’t been set.

  • a ||= b

The assignment statement supports a set of shortcuts. The expression a op= b is the same as a = a op b. This works for most operators:

Get hands-on with 1400+ tech skills courses.