Last Updated: February 25, 2016
·
873
· meagar

Conditionally wrap a variable in an array

These are ugly, but idomatic in many languages:

params = (params.is_a?(Array) ? params : [params])

or

params = [params] unless params.is_a?(Array)

Instead, Ruby provides Array(), which turns nil into [], leaves arrays untouched, and wraps everything else in an array:

# Make sure params is an array
params = Array(params)