Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coercing a scalar or an array to become an array

Tags:

ruby

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.

like image 475
Ken Barber Avatar asked Mar 11 '12 09:03

Ken Barber


2 Answers

Array(variable)

should do the trick. It uses the little known Kernel#Array method.

like image 154
lucapette Avatar answered Sep 24 '22 18:09

lucapette


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

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

[*variable1] #=> ["string"]
[*variable2] #=> ["element1", "element2"]
like image 29
sawa Avatar answered Sep 26 '22 18:09

sawa