Create or append to array in Ruby

RubyArrays

Ruby Problem Overview


foo ||= []
foo << :element

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

Ruby Solutions


Solution 1 - Ruby

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

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

Solution 2 - Ruby

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

(a ||= []).push(:element)

Solution 3 - Ruby

You also could benefit from the Kernel#Array, like:

# foo = nil
foo = Array(foo).push(:element)
# => [:element]

which has the benefit of flattening a potential Array, like:

# foo = [1]
foo = Array(foo).push(:element)
# => [1, :element]

Solution 4 - Ruby

Also a little more verbose for readability and without a condition:

foo = Array(foo) << :element

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamindfvView Question on Stackoverflow
Solution 1 - RubyDave NewtonView Answer on Stackoverflow
Solution 2 - RubymeubView Answer on Stackoverflow
Solution 3 - RubyChristian RolleView Answer on Stackoverflow
Solution 4 - RubyRimianView Answer on Stackoverflow