Search code examples
crystal-lang

Getting the first element of an empty Array


Given an array which has zero or one elements, how do I return either the first element or nil?

I have working code, but it is not very elegant:

class Category < ActiveRecord::Model
  adapter sqlite

  table_name "categories"

  primary id      : Int
  field parent_id : Int
  field name      : String

  # return a category or nil
  def self.root
    roots = where(criteria("parent_id").is_null)

    if roots.empty?
      nil
    else
      roots.first
    end⋅
  end
end

Solution

  • You can simply call first? on the array:

      def self.root
        where(criteria("parent_id").is_null).first?
      end