Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create or append to array in Ruby

Tags:

arrays

ruby

foo ||= [] foo << :element 

Feels a little clunky. Is there a more idiomatic way?

like image 850
amindfv Avatar asked Aug 28 '12 16:08

amindfv


People also ask

How do you append to an array in Ruby?

Ruby has Array#unshift to prepend an element to the start of an array and Array#push to append an element to the end of an array. The names of these methods are not very intuitive. Active Support from Rails already has aliases for the unshift and push methods , namely prepend and append.

How do you append an array to another array in Ruby?

In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.

How do I push multiple values to an array in Ruby?

Appending or pushing arrays, elements, or objects to an array is easy. This can be done using the << operator, which pushes elements or objects to the end of the array you want to append to. The magic of using << is that it can be chained.


2 Answers

(foo ||= []) << :element 

But meh. Is it really so onerous to keep it readable?

like image 185
Dave Newton Avatar answered Oct 21 '22 08:10

Dave Newton


You can always use the push method on any array too. I like it better.

(a ||= []).push(:element) 
like image 29
meub Avatar answered Oct 21 '22 06:10

meub