Add Item to an Array in Ruby, Even If the Variable Does Not Exist

Add Item to an Array in Ruby, Even If the Variable Does Not Exist

I have the following:

foo ||= []
foo << "bar"

And I am sure this can be done in one line, I just cannot find how.

Important is, that foo may, or may not exist. If it exists it is always an Array, if it does not exist, it must become an array and get a variable appended to it.

0

3 Answers

Like this:

(foo ||= []) << "bar"

The parenthesized bit returns foo if it already exists, or creates it if it doesn't, and then the << appends to it.

1

If you only want to add "bar" when foo is not already defined:

foo ||= ["bar"]

if you want to add "bar" regardless of whether or not foo already exists:

(defined? foo) ? foo << "bar" : foo = ["bar"]

However, in the latter case, I personally prefer the way the original code is written. Sure it can be done in one line, but I think the two line implementation is more readable.

4

What code are you writing where you're unsure if a local variable exists?

If it's something like

def procedural_method(array)
  result ||= []
  array.each do |array_item|
    result << bar(array_item)
  end
  result
end

then you could try a more functional programming approach

def functional_programming_method(array)
  array.map do |array_item|
    bar(array_item)
  end
end
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.