Rails order of blank element within array

Viewed 51

Assuming the following array:

["Palm nova", "", "Palm trad", "Palm discard", nil, "Palm actual"]  

the goal is to extract the first item of the list, that is not a blank "" or nil

The rails where clause allows to order the results based on one or more attributes, in asc or desc order. But where does that place the blank item when using Postgresql as the database?

Are "" and nil treated the same?

2 Answers

By definition empty strings are ordered by comparing them with the < and > operators, as stated in the docs:

... Ascending order puts smaller values first, where "smaller" is defined in terms of the < operator. Similarly, descending order is determined with the > operator

Are "" and nil treated the same?: No. Again, from the docs "By default, null values sort as if larger than any non-null value", so if you sort by DESC your NULL values will be at the beginning, if using ASC they'll be at the end.

Basically you can do three things;

  • Or to modify your query to omit NULL and/or empty strings when filtering them if possible,
  • Or to manipulate the resulting array to filter out nil and/or empty strings,
  • Or to add an ORDER BY clause to your query to make sure NULL and/or empty strings have always an identified order in the result.

the goal is to extract the first item of the list, that is not a blank "" or nil If you mean a database select you can exclude these via SQL:

.where("col IS NOT NULL AND col != ''").limit(1)

Ruby can also filter arrays in memory. Array#detect will filter and return the first match. Using the Rails Object#present? extension we can do the following:

["Palm nova", "", "Palm trad", "Palm discard", nil, "Palm actual"].detect(&:present?)
Related