Ken Barber Ken Barber - 4 months ago 9
Ruby Question

Coercing a scalar or an array to become an array

Sometimes I want a variable to always be an array, whether its a scalar or already an array.

So I normally do:

[variable].flatten


which is compatible with ruby-1.8.5, 1.8.7, 1.9.x.

With this method when
variable
is a string (
variable = "asdf"
), it gives me
["asdf"]
. If it's already an array (
variable = ["asdf","bvcx"]
), it gives me:
["asdf","bvcx"]
.

Does anyone have a better way? "Better" meaning more readable, more performant, succinct or more effective in other ways.

Answer

The way I do, and think is the standard way, is using [*...]:

variable1 = "string"
variable2 = ["element1", "element2"]

[*variable1] #=> ["string"]
[*variable2] #=> ["element1", "element2"]