foo ||= [] foo << :element
Feels a little clunky. Is there a more idiomatic way?
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.
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.
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.
(foo ||= []) << :element
But meh. Is it really so onerous to keep it readable?
You can always use the push method on any array too. I like it better.
(a ||= []).push(:element)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With