Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby one liner to pass arrays elements into a string with separator

Tags:

arrays

ruby

I have an array like this:

myarray = ['value1','value2','value3']

And I'm looking for a one element array like this:

mynewarray = ['value1|value2|value3']

I know how to do that using each and concatening in a string, but I'm wondering if there is a oneliner and beautiful Ruby way of doing so...

like image 799
Nobita Avatar asked Feb 27 '12 20:02

Nobita


2 Answers

You can use the Array#join method.

 myarray.join('|')

Array#join doc:

Returns a string created by converting each element of the array to a string, separated by sep.

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-")   #=> "a-b-c"
like image 68
vdeantoni Avatar answered Sep 20 '22 16:09

vdeantoni


Howsabout...

mynewarray = [myarray.join('|')]
like image 45
BaronVonBraun Avatar answered Sep 18 '22 16:09

BaronVonBraun