Ken Barber Ken Barber - 3 months ago 7x
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:


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

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

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


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

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

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