Gijs P
Gijs P

Reputation: 1470

Convert an empty array to nil inplace

I have the following code:

some_array = [] # Sometimes is filled, in this case it isn't
new_array = some_array || ['default', 'array', 'values']

Now, the || is not triggered, because [] != nil

Of course it can be solved by doing:

new_array = some_array
new_array = ['default', 'array', 'values'] if new_array.blank?

But I remember there is a function that does this in a single line, like:

[].filled_arr_or_nil # nil
['something'].filled_arr_or_nil # ['something']

Upvotes: 1

Views: 1850

Answers (2)

aburr
aburr

Reputation: 81

You can use something like this

some_array = []
new_array = some_array.empty? ? ['default', 'array', 'values'] : some_array

This is just a conditional statement that uses empty? to check if some_array contains any elements and then returns the desired output

Upvotes: 0

Gijs P
Gijs P

Reputation: 1470

I wasn't able to find the answer using a search engine, but StackOverflow gave me the answer with a similar question, but then about strings:

Converting an empty string to nil in place?

The solution is to use presence

Only available within Rails.

Upvotes: 4

Related Questions