Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
berkes Avatar asked Mar 09 '11 14:03

berkes


People also ask

How do you find if an element exists in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

What does .first do in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

How do you add an array to an array in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).


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.

like image 196
glenn mcdonald Avatar answered Sep 28 '22 06:09

glenn mcdonald


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.

like image 41
dbyrne Avatar answered Sep 28 '22 06:09

dbyrne


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
like image 22
Andrew Grimm Avatar answered Sep 28 '22 07:09

Andrew Grimm