amindfv
amindfv

Reputation: 8448

Create or append to array in Ruby

foo ||= []
foo << :element

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

Upvotes: 99

Views: 81676

Answers (4)

Rimian
Rimian

Reputation: 38418

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

foo = Array(foo) << :element

Upvotes: 2

Christian Rolle
Christian Rolle

Reputation: 1684

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]

Upvotes: 12

meub
meub

Reputation: 2308

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

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

Upvotes: 66

Dave Newton
Dave Newton

Reputation: 160181

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

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

Upvotes: 165

Related Questions